Home > DeveloperSection > Articles > this keyword in Java

this keyword in Java


Java Java 
Ratings:
0 Comment(s)
 549  View(s)
Rate this:

this keyword in Java

The this keyword is used when you need to use class global variable in the constructors. this is a reference to the current object — the object whose method or constructor is being called. You can refer to any member of the current object from within an instance method or a constructor by using this.

In java, this is a reference variable that refers to the current object. It is useful for a method to reference instance variables relative to this keyword. this is a keyword in Java. Which can be used inside method or constructor of class. It (this) works as a reference to current object whose method or constructor is being invoked. this keyword can be used to refer any member of current object from within an instance method or a constructor. 

The this keyword can be used to refer current class instance variable.

If there is ambiguity between the instance variable and parameter, this keyword resolves the problem of ambiguity.

this keyword with field(Instance Variable) -:

this keyword can be very useful in case of Variable Hiding. We can not create two Instance/Local Variable with same name. But it is legal to create One Instance Variable & One Local Variable or Method parameter with same name. In this scenario Local Variable will hide the Instance Variable which is called Variable Hiding.

Using this with a Constructor

public class Rectangle {

    private int x, y;

    private int width, height;

       

    public Rectangle() {

        this(0, 0, 1, 1);

    }

    public Rectangle(int width, int height) {

        this(0, 0, width, height);

    }

    public Rectangle(int x, int y, int width, int height) {

        this.x = x;

        this.y = y;

        this.width = width;

        this.height = height;

    }   

}

Example of this keyword as method parameter

public class Sample1 {

 public static void main(String[] args) {

 Sample2 obj = new Sample2 ();

 obj.i = 10;

 obj.method();

 }

}

class Sample2 extends Sample1 {

 int i;

 

 void method() {

 method1(this);

 }

 void method1(Sample2  t) {

 System.out.println(t.i);

 }

}

 

 

 


Don't want to miss updates? Please click the below button!

Follow MindStick