Explain about field hiding in java?

Java 8Object Oriented ProgrammingProgramming

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 subclass field hides the superclass’s field irrespective of the types. This mechanism is known as field 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.

 Live Demo

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

Still, if you need to access the fields of superclass you need to use the super keyword as −

Example

 Live Demo

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);
      System.out.println("Name: "+super.name);
      System.out.println("age: "+super.age);
   }
}
public class FieldHiding{
   public static void main(String args[]){
      new Sub().display();
   }
}

Output

Name: Vishnu
age: 22
Name: Krishna
age: 25
raja
Published on 05-Jul-2019 17:19:27
Advertisements