Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using 'this' keyword in Java constructors [duplicate]

Tags:

java

this

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?

like image 218
deepti awasthi Avatar asked Apr 01 '12 19:04

deepti awasthi


2 Answers

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.

like image 137
DaveFar Avatar answered Nov 11 '22 14:11

DaveFar


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)

like image 43
stefan bachert Avatar answered Nov 11 '22 15:11

stefan bachert