12

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?

Freek de Bruijn
  • 3,552
  • 2
  • 22
  • 28
deepti awasthi
  • 121
  • 1
  • 1
  • 3

8 Answers8

26

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.

DaveFar
  • 7,078
  • 4
  • 50
  • 90
7

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)

stefan bachert
  • 9,413
  • 4
  • 33
  • 40
6

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.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
3

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.

Andreas
  • 2,450
  • 1
  • 18
  • 20
3

It doesn't have to do anything with constructors, memory allocation or anything like that. this keyword is just current object instance reference.

Mike Samuel
  • 118,113
  • 30
  • 216
  • 245
maxk
  • 642
  • 1
  • 9
  • 21
1

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.

darrengorman
  • 12,952
  • 2
  • 23
  • 24
1

this signifies the instance itself regarldless of how the instance was built

SiN
  • 3,704
  • 2
  • 31
  • 36
0

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
}

Vinay Guru
  • 79
  • 1
  • 6
  • 19