Why doesn't Java allow overriding of static methods?

后端 未结 22 2693
谎友^
谎友^ 2020-11-21 05:49

Why is it not possible to override static methods?

If possible, please use an example.

22条回答
  •  无人共我
    2020-11-21 06:31

    Static methods are treated as global by the JVM, there are not bound to an object instance at all.

    It could conceptually be possible if you could call static methods from class objects (like in languages like Smalltalk) but it's not the case in Java.

    EDIT

    You can overload static method, that's ok. But you can not override a static method, because class are no first-class object. You can use reflection to get the class of an object at run-time, but the object that you get does not parallel the class hierarchy.

    class MyClass { ... }
    class MySubClass extends MyClass { ... }
    
    MyClass obj1 = new MyClass();
    MySubClass obj2 = new MySubClass();
    
    ob2 instanceof MyClass --> true
    
    Class clazz1 = obj1.getClass();
    Class clazz2 = obj2.getClass();
    
    clazz2 instanceof clazz1 --> false
    

    You can reflect over the classes, but it stops there. You don't invoke a static method by using clazz1.staticMethod(), but using MyClass.staticMethod(). A static method is not bound to an object and there is hence no notion of this nor super in a static method. A static method is a global function; as a consequence there is also no notion of polymorphism and, therefore, method overriding makes no sense.

    But this could be possible if MyClass was an object at run-time on which you invoke a method, as in Smalltalk (or maybe JRuby as one comment suggest, but I know nothing of JRuby).

    Oh yeah... one more thing. You can invoke a static method through an object obj1.staticMethod() but that really syntactic sugar for MyClass.staticMethod() and should be avoided. It usually raises a warning in modern IDE. I don't know why they ever allowed this shortcut.

提交回复
热议问题