javainheritancestaticpolymorphismmethod-hiding

Why static methods of Parent Class gets hidden in Child Class?


This is psuedo-code

class A
{
  public static void m1()
  {
    System.out.println("Parent");
  }
}

class B extends A
{
  public static void m1()
  {
    System.out.println("Child");
  }
}

This code compiles successfully. Having an @Override annotation throws a compilation error. So please explain the concept about method hiding. Does the Parent static method gets inherited in Child ?


Solution

  • A static method belongs to a class and not an instance of the class. For this reason, the call to a static method is always resolved using the reference type and not the instance type.

    Runtime polymorphism only applies to instance methods. Therefore, both the following calls to m1 in the example program will result in m1 from A being called.

    A aReferenece = new B(); 
    A.m1();  
    aReference.m1();
    

    Since the instance type doesn't have any role to play in deciding which method gets called, being able to override a static method makes no sense since the method call is resolved at compile time itself.

    That said, static methods can still be inherited and therefore be redefined/hidden by the subclass.