Java Inheritance – instance variables overriding

You can hide a field, but not override it.

Hiding means that a field will have a different value depending from which class it’s accessed. The field in the subclass will “hide” the field in the super-class, but both exists.

That’s an extremely bad practice to hide field, but works:

public class HideField {

    public static class A
    {   
        String name = "a";

        public void doIt1() { System.out.println( name ); };
        public void doIt2() { System.out.println( name ); };   
    }

    public static class B extends A
    {
        String name = "b";

        public void doIt2() { System.out.println( name ); };
    }

    public static void main(String[] args)
    {
        A a = new A();
        B b = new B();

        a.doIt1(); // print a
        b.doIt1(); // print a
        a.doIt2(); // print a
        b.doIt2(); // print b <-- B.name hides A.name
    }
}

Depending on whether the method was overriden, the field in A or B is accessed.

Never do that! That’s never the solution to your problem and creates very subtle bugs related to inheritance.

Leave a Comment