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.
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 parameters | must always be the same |
Return type of parameters | return type could be a subtype of the return type of the hidden method. |
Access level | may relax the constraints of the overridden method. |
List of checked exceptions in the throws clause | may relax the constraints of the overridden method. |
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(); } }