What is instance variable hiding in java?

In Java if there is a local variable with the same name as an instance variable in a method, then the local variable will hide the instance variable. If we want to reflect the changes made to the instance variables, we can use this reference to do so.

In Java, instance variable hiding occurs when a subclass declares an instance variable with the same name as an instance variable in its superclass. When this happens, the subclass instance variable "hides" the superclass instance variable, which means that references to the variable name from the subclass refer to the subclass instance variable, not the superclass instance variable.

For example, consider the following code:

public class SuperClass {
    int num = 10;
}

public class SubClass extends SuperClass {
    int num = 20;

    public void display() {
        System.out.println("SubClass num: " + num);
        System.out.println("SuperClass num: " + super.num);
    }
}

In this code, the SubClass declares an instance variable num with a value of 20. This variable "hides" the num instance variable in its superclass SuperClass, which has a value of 10. When the display() method is called, it prints the value of the num instance variable in SubClass and the num instance variable in SuperClass using the super keyword to access the superclass variable.

Instance variable hiding can cause confusion and unexpected behavior in code. It's important to be aware of this concept when working with inheritance in Java to avoid unintended consequences.

Submit Your Programming Assignment Details