lets assume that i have 2 classes.
ParentClass:
public class ParentClass {
public static void getInstance(){
System.out.println("Parent method");
}
}
ChildClass:
public class ChildClass extends ParentClass {
public static void getInstance(){
System.out.println("child method");
}
public static void main(String args[]){
ParentClass pc=new ChildClass();
pc.getInstance();
}
}
as you notice above both classes has a static method called getInstance()
and in java and many other languages if there is an inherited method and you have the same method in the child class the method that get executed is one in the child class.
the question is: why pc.getInstance();
calls the method in the parent class? yeah there is no method overriding for static methods but could anyone please explain more the weird behavior of pc instance and why does it refer to the parent method even tho its pointing on the child class??
and why is it allowed to call a static method with a reference to an instance of the class ?
Thanks
There is no method overriding for static methods. The static type of the instance being used to call the method (ParentClass
in your example) determines which method is called.
Besides that, it's bad practice to use an instance reference in order to call a static method. You should use ClassName.methodName()
to execute a static method.