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:


Inheritance:
* Syntax
* Inheritance and Static Methods

Table Of Contents
0 Inheritance
8 Arrays
10 Maps
11 Strings
25 JAXB
29 Enums
32 Audio
41 Scanner
63 Logging
75 Lists
78 Sets
89 JAX-WS
96 XJC
98 Process
106 Modules
114 Applets
122 JNDI
139 JavaBean
141 Literals
144 Packages
150 JMX
153 JShell
159 Sockets
167 Enum Map
175 Hashtable
177 SortedMap