Skip to content
Related Articles

Related Articles

Instance Variable Hiding in Java

View Discussion
Improve Article
Save Article
Like Article
  • Difficulty Level : Basic
  • Last Updated : 11 Apr, 2022

One should have a strong understanding of this keyword in inheritance in Java to be familiar with the concept. Instance variable hiding refers to a state when instance variables of the same name are present in superclass and subclass. Now if we try to access using subclass object then instance variable of subclass hides instance variable of superclass irrespective of its return types.

In Java, if there is a local variable in a method with the same name as the 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.

Example:

Java




// Java Program to Illustrate Instance Variable Hiding
  
// Class 1
// Helper class
class Test {
  
    // Instance variable or member variable
    private int value = 10;
  
    // Method
    void method() {
  
        // This local variable hides instance variable
        int value = 40;
  
        // Note: this keyword refers to the current instance
  
        // Printing the value of instance variable
        System.out.println("Value of Instance variable : "
                           + this.value);
  
        // Printing the value of local variable
        System.out.println("Value of Local variable : "
                           + value);
    }
}
  
// Class 2
// Main class
class GFG {
  
    // Main driver method
    public static void main(String args[]) {
  
        // Creating object of current instance
        // inside main() method
        Test obj1 = new Test();
  
        // Callling method of above class
        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 review-team@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.


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!