Java-This Keyword

This Keyword

Java defines the this keyword. this can be used inside any method to refer to the current object. That is, this is always a reference to the object on which the method was invoked. You can use this anywhere  a reference to an object of the current class’ type is permitted.

As you know, it is legal to declare local variables with the same name of the instance variable. Interestingly, you can have local variables, including formal parameters to methods, which overlap with the names of the class’ instance variables. However, when a local variable has the same name as an instance variable, the local variable hides the instance variable. While it is usually easier to simply use different names, there is another way around this situation. Because this lets you refer directly to the object, you can use it to resolve any name space collisions that might occur between instance variables and local variables. For example, in the following program, setAwithThis( ) method uses ‘a’ for parameter names and then uses this to access the instance variables by the same name.

Program

gdgdfgf

Program Source

class Data{
    
    private int a;
    
    void setA(int a)
    {
        a = a;
    }
    
    void setAwithThis(int a)
    {
        this.a = a;
    }
    
    void printA()
    {
        System.out.println("a = "+a);
    }
}

public class Javaapp {
    
    public static void main(String[] args) {
        
        Data d1 = new Data();
        d1.setA(50);
        d1.printA();
        d1.setAwithThis(50);
        d1.printA();
    }
}

Leave a Comment