Inheritance and Static Methods

suggest change

In Java, a parent class and a child class can both have static methods with the same name. The child’s method hides the parent’s implementation; it does not override it. 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 bound to a class, not to an instance, and that choice is made at compile time. The first call uses the reference type Parent, so Parent’s staticMethod() runs. The cast changes the compile-time type to Child, so Child’s staticMethod() runs.

Feedback about page:

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



Table Of Contents