Overriding vs Hiding

  • Overriding is based on late binding (decided at runtime)
  • Hiding is based on early binding (decided at compile time)
  • Overriding examples:
    • non-static methods
  • Hiding examples:
    • static methods
    • instance fields
    • static fields
  • In hiding compiler only checks the declared type (datatype of the object) to determine which method/field to invoke
  • It is not recommended to hide fields
  • Hiding of fields happen even if their types are different
  • ref: https://www.coderanch.com/wiki/659959/Overriding-Hiding
class Parent {
	// hiding
    public String name = "Parent";
    //hiding
    public static String staticName = "Parent";
    
    // only this supports overriding
    public String getName() {
        return "Parent";
    }
    // hiding
    public static String getStaticName() {
        return "Parent";
    }
}
 
class Child extends Parent {
    public String name = "Child";
    public static String staticName = "Child";
    public String getName() {
        return "Child";
    }
    public static String getStaticName() {
        return "Child";
    }
}
 
public class App {
    public static void main(String[] args) throws Exception {
        Parent obj = new Child();
        
        // Hiding non-static field + Hiding static field
        System.out.println(obj.name + " " + obj.staticName);
        // Parent Parent
 
        // Override non-static method + Hiding static method
        System.out.println(obj.getName() + " " + obj.getStaticName());
        // Child Parent
    }  
}