Java - Inheritance Method Hiding

What is Method Hiding?

Redefining an inherited static method in a class is known as method hiding.

The redefined static method in a subclass hides the static method of its superclass.

Redefining a non-static method in a class is called method overriding.

Rule

All rules about the redefined method for method hiding are the same as for method overriding.

Item Rule
Name of the method must always be the same
Number of parameters must always be the same
Type of parameters must always be the same
Order of parametersmust always be the same
Return type of parameters return type could be a subtype of the return type of the hidden method.
Access levelmay relax the constraints of the overridden method.
List of checked exceptions in the throws clausemay relax the constraints of the overridden method.

Demo

class MySuper {
  public static void print() {
    System.out.println("Inside MySuper.print()");
  }//from   w w  w . jav a2s  .  c o m
}

// A MySub Class That Hides the print() of its Superclass
class MySub extends MySuper {
  public static void print() {
    System.out.println("Inside MySub.print()");
  }
}

public class Main {
  public static void main(String[] args) {
    MySuper mhSuper = new MySub();
    MySub mhSub = new MySub();
    System.out.println("#1");

    // #1
    MySuper.print();
    mhSuper.print();

    System.out.println("#2");

    // #2
    MySub.print();
    mhSub.print();
    ((MySuper) mhSub).print();

    System.out.println("#3");

    // #3
    mhSuper = mhSub;
    mhSuper.print();
    ((MySub) mhSuper).print();
  }
}

Result