Difference between "field" and "this.field" in Java - java

I'd like to better understand what is the difference in referring to a class field by using this.field and field alone as in
this.integerField = 5;
and
integerField = 5;

this keyword refers to the current object.
usually we use this.memberVariable to diffrentiate between the member and local variables
private int x=10;
public void m1(int x) {
sysout(this.x)//would print 10 member variable
sysout(x); //would print 5; local variable
}
public static void main(String..args) {
new classInst().m1(5);
}
Off from the concrete question,
the use of this In Overloaded constructors:
we can use this to call overloaded constructor like below:
public class ABC {
public ABC() {
this("example");to call overloadedconstructor
sysout("no args cons");
}
public ABC(String x){
sysout("one argscons")
}
}

The use of this keywords lets you disambiguate between member variables and locals, such as function parameters:
public MyClass(int integerField) {
this.integerField = integerField;
}
The code snippet above assigns the value of local variable integerField to the member variable of the class with the same name.
Some shops adopt coding standards requiring all member accesses to be qualified with this. This is valid, but unnecessary; in cases where no collision exists, removing this does not change the semantic of your program.

When you are in an instance method, you may need to specify to which scope you refer a variable from. For example :
private int x;
public void method(int x) {
System.out.println("Method x : " + x);
System.out.println("Instance x : " + this.x);
}
While, in this example, you have two x variables, one is a local method variable and one is a class variable. You may distinguish between the two with this to specify it.
Some people always use this before using a class variable. While it is not necessary, it may improve code readability.
As for polymorphism, you may refer to the parent class as super. For example :
class A {
public int getValue() { return 1; }
}
class B extends A {
// override A.getValue()
public int getValue() { return 2; }
// return 1 from A.getValue()
// have we not used super, the method would have returned the same as this.getValue()
public int getParentValue() { return super.getValue(); }
}
Both keywords this and super depend on the scope from where you are using it; it depends on the instance (object) you are working with at run-time.

It's exactly the same. Because you often type this.xyz it's a shortcut that means the same thing if there is a field by that name and there isn't a local variable that shadows it.

Though they look and act the same, there is a difference when the same name is shared between a field and a method argument, e.g.:
private String name;
public void setName(String name){
this.name = name;
}
name is the passed parameter, and this.name is the proper class field.
Notice that typing this.... prompts you a list of all the class fields [and methods] in many IDEs.

From the Java tutorials:
Within an instance method or a constructor, this is a reference to the
current object — the object whose method or constructor is being
called. You can refer to any member of the current object from within
an instance method or a constructor by using this.
So, when you call a method within a object the call looks like this:
public class MyClass{
private int field;
public MyClass(){
this(10); // Will call the constructor with a int argument
}
public MyClass(int value){
}
//And within a object, the methods look like this
public void myMethod(MyClass this){ //A reference of a object of MyClass
this.field = 10; // The current object field
}
}

Related

Use of "this" operator in Java

Is there any other use of this keyword other than accessing member variable having the same name as local variable
this.x = x
Is there any other situation where it make sense to use this keyword.
One other use of this keyword is in constructor chaining, for example:
class Person {
private String name;
private int age;
public Person() {
//Invoking another constructor
this("John", 35);
}
public Person(String name, int age) {
this.name = name;
this.age = age;
}
}
You can pass the current object as a parameter to another method.
Below points have been taken from Java docs
The most common reason for using the this keyword is because a field is shadowed by a method or constructor parameter.
From within a constructor, you can also use the this keyword to call another constructor in the same class.
this represents the current instance inside the instance.
It is useful for:
identifying instance variables from locals (including parameters)
it can be used by itself to simply refer to member variables and methods, invoke other constructor overloads.
refer to the instance.
Some examples of applicable uses (not exhaustive):
class myClass
{
private int myVar;
public myClass() {
this(42); // invoke parameterized constructor of current instance
}
public myClass(int myVar) {
this.myVar = myVar; // disambiguate
}
public void another() {
this.second(); // used "just because"
}
private void second() {
System.out.println("whatever");
}
}
You can reference a field or call a method of an enclosing class
public class Examples {
public class ExamplesInner {
private int x;
public ExamplesInner() {
x = 3; // refers to ExamplesInner.x
Examples.this.x = 3; // refers to Examples.x
}
}
private int x;
}
For full usage, read the java language specification
The keyword this may be used only in the body of an instance method,
instance initializer, or constructor, or in the initializer of an
instance variable of a class. If it appears anywhere else, a
compile-time error occurs.
When used as a primary expression, the keyword this denotes a value
that is a reference to the object for which the instance method was
invoked (§15.12), or to the object being constructed.
The type of this is the class C within which the keyword this occurs.
At run time, the class of the actual object referred to may be the
class C or any subclass of C.
The keyword this is also used in a special explicit constructor
invocation statement, which can appear at the beginning of a
constructor body (§8.8.7).
this keyword can be used to refer current class instance variable.
this() can be used to invoke current class constructor.
this keyword
can be used to invoke current class method (implicitly)
this can be
passed as an argument in the method call.
this can be passed as
argument in the constructor call.
this keyword can also be used to
return the current class instance.
find examples from this:
http://javarevisited.blogspot.in/2012/01/this-keyword-java-example-tutorial.html
The this operator is used as reference to currently executing object. It is concerned with objects, and hence cannot be and should not be used with static references, where classes are used instead of objects.
The this operator can be used to invoke the constructor like this()
The this operator also avoids naming ambiguities and can be used to pass the current object as reference to functions
this lets you disambiguate between the private member foo and the parameter foo passed into the constructor: EX
class bar
{
private int foo;
public Foo(int foo)
{
this.foo =foo;
}
}

Why 'this' is not allowed in static methods?

I know this represents the object invoking the method and static methods are not bound to any object but my question is still you can invoke static method on class object .
Why java has made this thing available and not for this ?
this points to the current instance of the class.
Static methods are associated with a class, not an instance, so there's nothing for this to point to.
Here's an example:
public class Foo {
private String name;
public static void someClassMethod() { System.out.println("associated with a class"); }
public Foo(String n) { this.name = n; }
public String getName() { return this.name; }
public void setName(String n) { this.name = n; }
public void doAnotherThing() {
Foo.someClassMethod(); // This is what is really happening when you call a static method in an non-static method.
}
}
Simple answer: this is not defined outside of a non-static method.
Calling static methods on an instance is a syntactic shorthand, which I don't agree should exist.
From every point of view this always means this object, so giving possibility for meaning this class could lead to multiple bugs
The difference here is between a class and an object. A non-static method is called on an object, while a static method is Called on a class.
You can see a Class as a blueprint, with which Objects are built.
A class House has a static method hasDoor() (which will return true), while an object of the type House can have a method openDoor(). You can't open the door of a blueprint.
One can call House.hasDoor(), but not House.openDoor(). One can call
House h = new House();
h.openDoor();
While you can call h.hasDoor(), this is a bit nasty and should be avoided in most cases

java this keyword

I have read that in Java you don't have to explicitly bind the this keyword to object, it is done by interpreter. It is opposite to Javascript where you always have to know the value of this. But where is this in Java is pointing - to class or object ? Or does it vary ?
This question is a part of my attempt to understand basic OO concepts and design patterns so I can apply them to Javascript.
Thank you.
In Java, this always refers to an object and never to a class.
The Java language specification states:
When used as a primary expression, the keyword this denotes a value
that is a reference to the object for which the instance method was
invoked (§15.12), or to the object being constructed.
I.e. it always points to an object, not a class.
in java this is refer Current object
like
public class Employee{
String name,adress;
Employee(){
this.name="employee";
this.address="address";
}
}
this refers to current object.
Within an instance method or a constructor, this is a reference to the current object — the object whose method or constructor is being called. You can refer to any member of the current object from within an instance method or a constructor by using this.
In java 'this' is a keyword, basically used to refer to the current object. In the following example the setter methods are using 'this' to set the values of name and age of current object.
public class Person {
String name;
int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public static void main(String[] args) {
Person p = new Person();
p.setName("Rishi");
p.setAge(23);
System.out.println(p.getName() + " is " + p.getAge() + " years old");
}
}
From the official documentation (found here):
Within an instance method or a constructor, this is a reference to
the current object — the object whose method or constructor is being
called. You can refer to any member of the current object from within
an instance method or a constructor by using this.
What this means is that inside the code of any class, when you write this, you specify the fact that you are referring to the current object.
As a side note, you cannot use this with static fields or methods because they do not belong to any specific object (instance of the class).
this keyword is always used in referencing the object of the current class.
where as this() is used for the current class constructors.
for example:
class circle {
public int radius;
public Circle() {
this.radius = 10; //any default value
}
public Circle(int radius) {
this.radius = radius // here this.radius will set instance variable radius
}
public int areaOfCircle() {
return 3.14*radius*radius;
}
}

what is this() ? can it have multiple parameters?

I encountered a code where this() method in java takes three parameters two being integers and the third one is boolean value.
what exactly does that mean ? Are there any other variants of this() method ?
Hera is the actual code.
public SegmentConstructor(int seqNum_, int length_) {
this(seqNum_, length_, false);
}
Thank You..
It means that there is another constructor in the current class that has that signature.
public SegmentConstructor(int seqNum_, int length_) {
this(seqNum_, length_, false); // calls the constructor below.
}
public SegmentConstructor(int seqNum_, int length_, boolean required_) {
seqNum = seqNum_;
length = length_;
required = required_;
}
The this method is just a way to call one of your class's constructors from within another constructor, to help avoid code duplication. It can only be called on the first line of a constructor--never from within any other method.
this simply invokes another constructor to run. So, look for other constructors with that signature.
As said before this invokes another constructor, mostly as a convenience method.
Trivial example:
class A {
private int value;
public A(int val) {
value = val;
}
public A() {
this(0); //0 as default
}
}
Normally you do use calls to this() when the most specific constructor (that one with the most parameters) is not just assignment but contains more logic that you don't want to repeat/copy etc.
Just because it fits in here: super() can have parameters, too, i.e. this calls a super class' constructor with parameters from the sub class' constructor.
It is a constructor call. If your class implements different constructors with a differing number of arguments, you can chain your constructors like this:
class A {
public A(boolean arg) {
...
}
public A() {
this(false); // invokes the constructor with the boolean argument
}
}
Sometimes it makes sense to create a private constructor taking different arguments and provide public and/or protected constructors with other/fewer arguments and delegate object construction to that private constructor.
It is important to know that no other code may be placed before the call to this(...). However, after calling this(...), you can do everything you could in any other constructor.
Edit: Since this(...) calls a constructor, it can only be called from within other constructors (belonging to the same class).
class MyClass
{
private int var1;
private int var2;
private boolean flag;
public MyClass(int var1_,int var2_)
{
this(var1_,var2_,false);
}
public MyClass(int var1_,int var2_,boolean flag_)
{
var1 = var1_;
var2 = var2_;
flag = flag_;
}
public String toString()
{
return (new Boolean(flag).toString());
}
public static void main(String[] args)
{
MyClass my = new MyClass(5,6);
System.out.println(my);
}
}
So it works.
this() is not a method but is a reserved keyword pointing to a overloaded constructor of the same class.
The number of parameters you pass should point to an existing corresponding constructor defined in the class.
The super() also has the semantics however the constructor is defined in one of its parent hierarchy.

Overriding a super class's instance variables

Why are we not able to override an instance variable of a super class in a subclass?
He perhaps meant to try and override the value used to initialize the variable.
For example,
Instead of this (which is illegal)
public abstract class A {
String help = "**no help defined -- somebody should change that***";
// ...
}
// ...
public class B extends A {
// ILLEGAL
#Override
String help = "some fancy help message for B";
// ...
}
One should do
public abstract class A {
public String getHelp() {
return "**no help defined -- somebody should change that***";
}
// ...
}
// ...
public class B extends A {
#Override
public String getHelp() {
return "some fancy help message for B";
// ...
}
Because if you changed the implementation of a data member it would quite possibly break the superclass (imagine changing a superclass's data member from a float to a String).
Because you can only override behavior and not structure. Structure is set in stone once an object has been created and memory has been allocated for it. Of course this is usually true in statically typed languages.
Variables aren't accessed polymorphically. What would you want to do with this that you can't do with a protected variable? (Not that I encourage using non-private mutable variables at all, personally.)
class Dad{
public String name = "Dad";
}
class Son extends Dad{
public String name = "Son";
public String getName(){
return this.name;
}
}
From main() method if you call
new Son().getName();
will return "Son"
This is how you can override the variable of super class.
Do you mean with overriding you want to change the datatype for example?
What do you do with this expression
public class A {
protected int mIndex;
public void counter(){
mIndex++;
}
}
public class B extends A {
protected String mIndex; // Or what you mean with overloading
}
How do you want to change the mIndex++ expression without operator overloading or something like this.
If you have the need to override an instance variable, you are almost certainly inheriting from the worng class.
In some languages you can hide the instance variable by supplying a new one:
class A has variable V1 of type X;
class B inherits from A, but reintroduces V1 of type Y.
The methods of class A can still access the original V1. The methods of class B can access the new V1. And if they want to access the original, they can cast themself to class A (As you see dirty programming provokes more dirty progrtamming).
The best solution is to find another name for the variable.
you can override a method,that is all right
but what do you mean by overriding a variable?
if you want to use a variable at any other place rather than super class
u can use super.
as in
super(variable names);
why do you want to override a variable?
i mean is there any need?
we can not overriding structure of instance variables ,but we ovverride their behavior:-
class A
{
int x = 5;
}
class B extends A
{
int x = 7:
}
class Main
{
public static void main(String dh[])
{
A obj = new B();
System.out.println(obj.x);
}
}
in this case output is 5.

Categories

Resources