Image

Java - Core Java - this keyword

this keyword

The this keyword can be used to refer to any member of the current object from within an instance method or a constructor. ‘this’ is an internal or implicit object created by JAVA for two purposes. They are this object is internally pointing to current class object.

Whenever the formal parameters and data members of the class are similar, to differentiate the data members of the class from formal parameters, the data members of class must be preceded by ‘this’.

We can use this keyword in following ways
  • this variable
  • this constructor
  • this method
  • this variable

    this keyword can be very useful in the handling of Variable Hiding. We can not create two instance or local variables with the same name.

    class Test
    {
        int a;
        int b;
        Test(int a, int b) {
            this.a = a;
            this.b = b;
        }
     
        void display() {
            //Displaying value of variables a and b
            System.out.println("a = " + a + "  b = " + b);
        }
     
        public static void main(String[] args) {
            Test object = new Test(40, 80);
            object.display();
        }
    }
    Output
    a = 40  b = 80

    this constructor

    this keyword can be used inside the constructor to call another overloaded constructor in the same class.

    class Data
    {
        int a;
        int b;
        Data()
        {
            this(10,20);
        } 
        Data(int x,int y)
        {
            a=x;
            b=y;
        }
        void show()
        {
            System.out.println("a="+a);
            System.out.println("b="+b);
        }
            
    }
    public class ThisConstructor {
        public static void main(String[] args) {
            Data d1=new Data();
            Data d2=new Data(100,200);
            d1.show();
            d2.show();
        }   
    }
    Output
    a=10
    b=20
    a=100
    b=200

    this method

    this keyword can also be used inside Methods to call another method from same class.

    class Data
    {
        int a;
        int b;
        Data()
        {
            this(10,20);
        }
        Data(int x,int y)
        {
            a=x;
            b=y;
            this.show();
        }
        void show()
        {
            System.out.println("a="+a);
            System.out.println("b="+b);
        }
    }
    public class ThisMethod {
        public static void main(String[] args) {
     
            Data d1=new Data();
            Data d2=new Data(100,200);
            d1.show();
            d2.show();
        }
        
    }
    Output
    a=10
    b=20
    a=100
    b=200
    a=10
    b=20
    a=100
    b=200