Inheritance and Static Methods
suggest changeIn 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.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents