0

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

Ahmad Sanie
  • 3,678
  • 2
  • 21
  • 56

1 Answers1

4

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.

Eran
  • 387,369
  • 54
  • 702
  • 768
  • yeah there is no method overriding for static methods but could you please explain more the behavior of pc instance and why does it refer to the parent method even tho its pointing on the child class? Thanks – Ahmad Sanie Jan 11 '16 at 14:22
  • @AhmadAlsanie The static (compile time) type of `pc` is `ParentClass`. Therefore `pc.getInstance();` is equivalent to `ParentClass.getInstance();`. This will work even if `pc` is null. That's the behavior of static method invocation. – Eran Jan 11 '16 at 14:24
  • yeah i do understand that :) but my question is why! why is it designed to behave like this? – Ahmad Sanie Jan 11 '16 at 14:26
  • @AhmadAlsanie Because static methods are not tied to any instance of the class. Therefore the dynamic type of an instance of the class doesn't matter when invoking a static method. You should be asking why you are even allowed to call a static method with a reference to an instance of the class. I find that syntax to make little sense. – Eran Jan 11 '16 at 14:30
  • yup that what i was trying to say why is it allowed to call a static method with a reference to an instance of the class ? – Ahmad Sanie Jan 11 '16 at 14:54