• Register
60 views

I started learning java for a few days back. Now I am working on the object-oriented part, and learning the Object and Instance. I figure out the (this.) term in java. What does “this” mean in java? What does it do? Moreover, there are two types of ‘’’THIS’ here I can see. One is “this” and the other one is “this.

 

Solution:

this’ is a reference variable in java that refers to the current object of the main method. Let’s make it clear with an example below:

class MyClass 
{ 
    int x; 
    int y; 
      
    MyClass(int x, int y) 
    { 
        this.x = x; 
        this.y = y; 
    } 
  
    void display() 
    { 
        System.out.println("X = " + x + "  Y = " + y); 
    } 
  
    public static void main(String[] args) 
    { 
        MyClass object = new MyClass(5, 10); 
        object.display(); 
    } 
}

As you can see above we have an instance variable X and Y under MyClass. We also have a constructor that is parameterized by the variable X and Y. The (this.) keyword refers to the values of that two instance variables inside our constructor

 After that, we used our constructor by creating a new object ‘object’ inside the main function which leads us through getting the output     

posted Mar 18 in java by (13,900 points)  
...