What is instance variable hiding in Java?


Whenever you inherit a superclass a copy of superclass’s members is created at the subclass and you using its object you can access the superclass members.

If the superclass and the subclass have instance variable of same name, if you access it using the subclass object, the instance variables of the subclass hides the instance variables of the superclass irrespective of the types. This mechanism is known as field hiding or, instance variable hiding.

But, since it makes code complicated field hiding is not recommended.

Example

In the following example we have two classes Super and Sub one extending the other. They both have two fields with same names (name and age).

When we print values of these fields using the object of Sub. The values of the subclass are printed.

class Super {
   String name = "Krishna";
   int age = 25;
}
class Sub extends Super {
   String name = "Vishnu";
   int age = 22;
   public void display(){
      Sub obj = new Sub();
      System.out.println("Name: "+obj.name);
      System.out.println("age: "+obj.age);
   }
}
public class FieldHiding{
   public static void main(String args[]){
      new Sub().display();
   }
}

Output

Name: Vishnu
age: 22

Updated on: 30-Jul-2019

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements