Inheritance and Static Methods

suggest change

In Java, parent and child class both can have static methods with the same name. But in such cases implementation of static method in child is hiding parent class’ implementation, it’s not method overriding. For example:

class StaticMethodTest {

  // static method and inheritance
  public static void main(String[] args) {
    Parent p = new Child();
    p.staticMethod(); // prints Inside Parent
    ((Child) p).staticMethod(); // prints Inside Child
  }

  static class Parent {
    public static void staticMethod() {
      System.out.println("Inside Parent");
    }
  }

  static class Child extends Parent {
    public static void staticMethod() {
      System.out.println("Inside Child");
    }
  }
}

Static methods are bind to a class not to an instance and this method binding happens at compile time. Since in the first call to staticMethod(), parent class reference p was used, Parent’s version of staticMethod() is invoked. In second case, we did cast p into Child class, Child’s staticMethod() executed.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents