Using the 'this' keyword in Java constructors

I am confused with this in Java. If the class has two constructors and we use the this in some method, the object represented by this is created using which of the two constructors?

+6
source share
8 answers

You must distinguish between this. and this() , so to speak:

In most cases, you use this as a reference to the current object, i.e. the reference to this object is replaced at runtime for this . For example, if you use this as a parameter or this.someMember link.

You can have different constructors with different parameters, i.e. overload constructors. At the beginning of the constructor, you can call another constructor using this(parameter_1, ... parameter_n); as the first instruction.

A good explanation of both cases can be found in the java tutorial about this keyword .

+20
source

It is unimportant and indistinguishable

It is like making a car. Depending on the features, another constructor is used, but in the end you have a car (this)

+7
source

The this has two meanings, and confusion can be around these two meanings.

In the constructor, this(...) is like calling a method for constructors. The compiler chooses which constructor should call based on the number and types of arguments you use.

When you use this as a reference, it means that this object, and which constructor was used, does not matter.

+7
source

It should not do anything with constructors, memory allocation, or something like that. this keyword is just a reference of an object instance of an object.

+3
source

You can think of this as a placeholder. At run time, this keyword is exchanged with a reference to the object of the object you are dealing with.

+2
source

Using this inside the method body refers to an instance of the class in which the method exists.

This also means that this cannot be used from a static context.

+1
source

this means the instance itself, having no idea how the instance was created

+1
source

1.'this' The keyword refers to the object of the class in which it is used. In general, we write an instance variable, constructors, and methods in a class. All of these members are represented by 'this'.
2. When an object is created by a class, a reference to the object by default is also created inside the object. This is nothing but 'this'.
3. An example for this keyword:
Example (int x) // Parameterized Constructor {
this.x = x; // Saves the local variable x to the current instance variable of class x
}

0
source

Source: https://habr.com/ru/post/912187/


All Articles