-4

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.

2 Answers2

1

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.

Andy Thomas
  • 84,978
  • 11
  • 107
  • 151
0

You have to type this because in constructor's scope name of our variables a and b are hidden behind the names of parameters a and b. this means just the current object of the class.

EDIT: Object is created with new keyword. The x variable is just a reference to the object. In the class methods we can refer to the current object with this and somewhere else we have to make a reference. So when your teacher told about this refering to x he meant refering to the object which is accessible with x.

Wojtek
  • 1,288
  • 11
  • 16