Method Overriding (Cont.)


static Methods Not Being Overridden (or Method Hiding)
When you defines a static method with same signature as a static method in base class, it is known as method hiding. The following table summarizes what happens when you define a method with the same signature as a method in a superclass:

Superclass Instance Method Superclass Static Method
Subclass Instance Method Overrides Generates a compile-time error
Subclass Static Method Generates a compile-time error Hides

Hiding.java (method overriding vs method hiding)
// Program to demonstrate if a static method is redefined by
// a derived class, then it is hiding, instead of overriding
// Driver class 
class Hiding { 
  public static void main( String[ ] args ) { 
    Parent obj1 = new Child( ); 
    // As per overriding rules, the following command should call the
    // static overridden method of the class Child. 
    // Since static method can not be overridden, it calls Parent's m1( ).  
    obj1.m1( );  
    // Here overriding works and Child's m2( ) is called.  
    obj1.m2( );  
  } 
} 
class Parent {
  // Static method in base class which will be hidden in subclass. 
  static void m1( ) { System.out.println( "From parent static m1( )" ); } 
  // Non-static method which will be overridden in derived class.
  void m2( ) { System.out.println( "From parent non-static m2( )" ); } 
} 
class Child extends Parent { 
  // This method hides m1( ) in Parent.
  static void m1( ) { System.out.println( "From child static m1( )" ); } 
  // This method overrides m2() in Parent 
  @Override
  public void m2( ) { System.out.println( "From child non-static m2( )" ); } 
}
shell> java Hiding           Result: