Use of "this" keyword in java [duplicate]
I was studying method overriding in Java when ai came across the this
keyword. After searching much about this on the Internet and other sources, I concluded that thethis
keyword is used when the name of an instance variables is same to the constructor function
parameters. Am I right or wrong?
this
is an alias or a name for the current instance inside the instance. It is useful for disambiguating instance variables from locals (including parameters), but it can be used by itself to simply refer to member variables and methods, invoke other constructor overloads, or simply to refer to the instance. Some examples of applicable uses (not exhaustive):
class Foo
{
private int bar;
public Foo() {
this(42); // invoke parameterized constructor
}
public Foo(int bar) {
this.bar = bar; // disambiguate
}
public void frob() {
this.baz(); // used "just because"
}
private void baz() {
System.out.println("whatever");
}
}
this
keyword can be used for (It cannot be used with static methods):
- To get reference of an object through which that method is called within it(instance method).
- To avoid field shadowed by a method or constructor parameter.
- To invoke constructor of same class.
- In case of method overridden,
this
is used to invoke method of current class. - To make reference to an inner class. e.g
ClassName.this
- To create an object of inner class e.g
enclosingObjectReference.new EnclosedClass
You are right, but this is only a usage scenario, not a definition. The this
keyword refers to the "current object". It is mostly used so that an object can pass itself as a parameter to a method of another object.
So, for example, if there is an object called Person
, and an object called PersonSaver
, and you invoke Person.SaveYourself()
, then Person
might just do the following: PersonSaver.Save( this )
;
Now, it just so happens that this
can also be used to disambiguate between instance data and parameters to the constructor or to methods, if they happen to be identical.