This question already has an answer here:
- What is the meaning of “this” in Java? 18 answers
I am confused with the this
keyword in Java. If a class has two constructors and we use the this
keyword in some method, the object represented by this
is instantiated using which of the two constructors?
You have to distinguish between this.
and this()
, so to speak:
Most of the time, you use this
as the reference to the current object, i.e. the reference of this object is replaced at runtime for this
. For instance, if you use this
as parameter or reference this.someMember
.
You can have different constructors with different parameters, i.e. overload constructors. At the beginning of a constructor, you can call a different constructor by using this(parameter_1, ... parameter_n);
as first instruction.
A nice explanation of both cases can be found at the java tutorial about the this keyword.
It doesn't care and is indistinguishable
It is somewhat like building a car. Depending on the features an other constructor is used, but in the end you have a car (this)
The this
keyword has two meaning and the confusion could be around these two meanings.
In the constructor, this(...)
is like a method call for constructors. The compiler chooses which constructor to call based on the number and types of the arguments you use.
When you use this
as a reference, it means this object, and which constructor was used is not important.
You can think of the this
keyword as a placeholder. At runtime that keyword is exchanged with the object reference of the object you are dealing with.
It doesn't have to do anything with constructors, memory allocation or anything like that. this
keyword is just current object instance reference.
Using this
within a method body refers to the instance of the class in which the method exists.
This also implies that this
cannot be used from a static
context.
this
signifies the instance itself regarldless of how the instance was built
1.'this' Keyword refers to object of class where it is used.Generally we write instance variable,constructors and methods in class.All this members are represented by 'this'.
2.When an object is created to a class,a default reference is also created internally to the object.It's nothing but 'this'.
3.Example for this keyword:
Sample(int x)//Parameterized Constructor{
this.x=x;//Stores local variable x into present class instance variable x
}
来源:https://stackoverflow.com/questions/9967437/using-this-keyword-in-java-constructors