Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reason for not supporting dynamic polymorphism for static methods in Java

Why does not Java support dynamic polymorphism for static methods? If the answer is "static methods are not supposed to be called on instances and hence method call is not needed to be resolved at runtime", then further question is 'Why does Java allow me to call static methods on instances?'. Why doesn't it simply block the user from calling the method on instances directly by giving some compile time error.

Otherway round, What would have gone wrong if Java would have supported Runtime Polymorphism for static methods?

like image 638
Tushar Baviskar Avatar asked Sep 22 '26 00:09

Tushar Baviskar


2 Answers

Why does Java allow me to call static methods on instances?

Your assumption is wrong. It never calls on the instance of the class. It always called on class.

Try below sample code and you will never get NullPointerException

class ABC {
    public static void hello() {
        System.out.println("Hello");
    }
}

ABC abc = null;
abc.hello(); 

What would have gone wrong if Java would have supported Runtime Polymorphism for static methods?

Polymorphism comes into picture when you override the method in subclass. since static method belong to class hence there is no meaning of overriding static methods. Hence Polymorphism always works for instance methods only that belongs to the instances of the class.

like image 58
Braj Avatar answered Sep 24 '26 16:09

Braj


Static methods are resolved based on a variable's type and not the instance's class. This allows for some optimisations, since the exact method to be called is always known at compile time. Allowing polymorphic static methods would prevent this.

A result of allowing static methods to be called on instances is the following.

class A {
    static void func() {}
}

class B extends A {
    static void func() {}
}

B b = new B();
A a = b;

b.func(); // calls B.func()
a.func(); // same instance, but calls A.func()

Highly confusing, and counter intuitive. Based on how static methods were implemented allowing static methods to be called on instances was a major design flaw and should always be avoided.

By definition static methods do not require an instance to be called. By allowing polymorphic calls you require an instance, and if you require an instance to determine which method to call then why is the method static?

like image 34
Dunes Avatar answered Sep 24 '26 17:09

Dunes



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!