Java - Inheritance Field Hiding

What is Field Hiding

A static or non-static field declaration in a class hides the inherited field with the same name in its superclass.

Rule

The type of the field and its access level are not considered during field hiding.

Field hiding occurs only based on the field name.

  • Field hiding occurs when a class declares a variable with the same name as an inherited variable from its superclass.
  • Field hiding occurs only based on the name of the field.
  • A static field can hide an instance field.
  • A field of int type can hide a field of String type.
  • A private field in a class can hide a protected field in its superclass.
  • A public field in a class can hide a protected field in its superclass.
  • A class should use the keyword super to access the hidden fields of the superclass.
  • The class can use the simple names to access the redefined fields in its body.
class G {
        protected int x = 200;
        protected String y = "Hello";
        protected double z = 10.5;
}

class H extends G {
        protected int x = 400;       // Hides x in class G
        protected String y = "Bye";  // Hides y in class G
        protected String z = "OK";   // Hides z in class G
}

Demo

class MySuper {
  protected int num = 100;
  protected String name = "Tom";
}

class MySub extends MySuper {
  public void print() {
    System.out.println("num: " + num);
    System.out.println("name: " + name);
  }//from  www .j  a v a  2  s. com
}

class MySub2 extends MySuper {
  // Hides num field in MySuper class
  private int num = 200;

  // Hides name field in MySuper class
  private String name = "Wally Inman";

  public void print() {
    System.out.println("num: " + num);
    System.out.println("name: " + name);
  }
}

class MySub3 extends MySuper {
  // Hides the num field in MySuper class
  private int num = 200;

  // Hides the name field in MySuper class
  private String name = "Wally Inman";

  public void print() {
    // MySub3.num
    System.out.println("num: " + num);

    // MySuper.num
    System.out.println("super.num: " + super.num);

    // MySub3.name
    System.out.println("name: " + name);

    // MySuper.name
    System.out.println("super.name: " + super.name);
  }
}

public class Main {
  public static void main(String[] args) {
    MySub fhSub = new MySub();
    fhSub.print();

    MySub2 fhSub2 = new MySub2();
    fhSub2.print();

    MySub3 fhSub3 = new MySub3();
    fhSub3.print();
  }
}

Result