Rida Batool Rida Batool - 2 months ago 13
Java Question

java this keyword inside constructor

i am currently taking java class, and today my teacher said something that my mind didn't accepted i could be wrong. following code ,

class Ab{
int x;
int b;

public Ab(int x, int b){
this.x = x;
this.b = b;
}


public static void main(String[] args){
Ab x = new Ab(4,5); // this is where my teacher confused me

}
}


my teacher said
x Ab = new AB(4,5);
will get x object invoking constructor passed in constructor to refer to it with
this keyword
, what about anonymous classes like
new Ab(2,4);
now what will
this keyword
refers to? in my point of view
this
inside constructor has no link with reference variable until constructor create the object and return the reference to variable.

Answer

what about anonymous classes like new Ab(2,4);

This is not an anonymous class. It's an expression that creates a new object of type AB. The value of that expression is a reference to the object. The value of this within the AB constructor is a reference to the object. And the value of x below is a reference to the object. They're all references to the same object.

Ab x = new Ab(4,5); // this is where my teacher confused me

in my point of view this inside constructor has no link with reference variable until constructor create the object and return the reference to variable.

The this inside the constructor has no need to refer to another reference variable. It points to the same object as x will when the constructor returns.

A reference is not the object itself. You can think it of one of possibly multiple pointers to an object.

Comments