Hiding vs overriding

What is the difference between hiding (fields) and overriding (methods)? Let’s look at the following two classes:


    public class A {
        public String name = "Class A";
        public String getName(){
            return this.name;
        }
    }
    public class B extends A {
        public String name = "Class B";
        public String getName(){
            return this.name;
        }
    }

Now look at the following code snippet and guess the output:


    A a = new B();
    System.out.println(a.name);
    System.out.println(a.getName());

Click here to see the output. Child class overrides the method of the parent class but hides the instance field that has the same name in the parent class.

The difference between hiding and overriding is caused by the fact that the hiding is resolved at compile-time, while the overriding is resolved at runtime. 

That’s why, to avoid confusion, it is recommended that all the instance fields should be declared as private and their values accessed only via setters and getters. This way the accessibility of the instance fields is governed by the rules of the overriding too, not the rules of hiding.

Notice that we talked only about instance fields and methods. The static class members do not have such a discrepancy in behavior as the instance class members. Both – static fields and static methods of a child class hide static fields and methods of the parent class.

Consider the following classes:

   public class C {
        public static String name = "Class C";
        public static String getName(){
            return name;
        }
    }
    public class D extends C {
        public static String name = "Class D";
        public static String getName(){
            return name;
        }
    }

The following code snippet shows that both – static fields and static methods – are subjects of the rules of hiding:

    C c = new D();
    System.out.println(c.name);       //prints: Class C
    System.out.println(c.getName());  //prints: Class C

So, there is no need to access static fields via static setters and getters to provide consistency of the accessibility between static fields and static methods.

Read more detailed discussion of this topic in the following books:

Send your comments using the link Contact or in response to my newsletter.
If you do not receive the newsletter, subscribe via link Subscribe under Contact.

Powered by WordPress. Designed by Woo Themes