Question regarding result of "No late binding for static methods" [Java]

Viewed 67

Given the code from Parent class and Child class:

class Parent{

   public static void classMethod(){
      System.out.println("ClassMethod in Parent"); 
   }

   public void hello(){
      System.out.println("Hello from parent, call classMethod");
      classMethod();
   }
}
class Child extends Parent{

   public static void classMethod(){
      System.out.println("ClassMethod in Child"); 
   } 

}

If I have this in main method:

public static void main(String[] arg) {
   Parent D = new Child(); 
   D.hello();
}

Why is this the result? ->

Hello from parent, call classMethod 
ClassMethod in Parent

So there's a child object of parent class calling an instance method which calls a static method. I would understand why it calls the static method from the parent class if hello() was static as well, since the object type would be defined at compile time and it would be Parent. However, since hello() here is an instance method, it has to be resolved at runtime, and at runtime, isn't the type of the object the actual type, AKA Child type? So in that case, wouldn't it call the static method from the child object since the object is of child type at run time?

1 Answers

Note: this answer assumes the Child class extends Parent. Otherwise, the code in the main method just throws an error.

This is an example of up-casting and polymorphism. Because it's of the type Parent, its access is limited to the Parent class. When you call the hello() method, it is being called in the Parent class. Then, this method calls classMethod() but, because hello() is a method in the parent class, it calls it in the Parent class as well, which is why you are getting that as a result. The fact that it is static makes no difference: static methods can always be called by instance methods, but not always the other way around.

One thing I should point out is that, because of the line Parent D = new Child();, the object D does not actually have access to any of the static methods in Child even though it is that type. If you wish for D to have access to methods in both Parent and Child, you can use Child D = new Child();

With Parent D = new Child();, if you are calling a method, it must be in the Parent class and will run the method in the parent class - except for if there is an overriding instance method of the same name in the Child class, in which case it will run this method instead. It should also be noted that an overridden method cannot be static

Related