Instance Variable Hiding in Java

1.2

In Java, if there a local variable in a method with same name as instance variable, then the local variable hides the instance variable. If we want to reflect the change made over to the instance variable, this can be achieved with the help of this reference.

class Test
{
    // Instance variable or member variable
    private int value = 10; 

    void method()
    {
        // This local variable hides instance variable
        int value = 40;

        System.out.println("Value of Instance variable :"
                            + this.value);
        System.out.println("Value of Local variable :"
                            + value);
    }
}

class UseTest
{
    public static void main(String args[])
    {
        Test obj1 = new Test();
        obj1.method();
    }
}

Output:

Value of Instance variable :10
Value of Local variable :40

This article is contributed by Twinkle Tyagi. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above

GATE CS Corner    Company Wise Coding Practice

Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.

Recommended Posts:



1.2 Average Difficulty : 1.2/5.0
Based on 53 vote(s)










Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.