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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With