Why doesn't Java allow overriding of static methods?

后端 未结 22 2741
谎友^
谎友^ 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:24

    Method overriding is made possible by dynamic dispatching, meaning that the declared type of an object doesn't determine its behavior, but rather its runtime type:

    Animal lassie = new Dog();
    lassie.speak(); // outputs "woof!"
    Animal kermit = new Frog();
    kermit.speak(); // outputs "ribbit!"
    

    Even though both lassie and kermit are declared as objects of type Animal, their behavior (method .speak()) varies because dynamic dispatching will only bind the method call .speak() to an implementation at run time - not at compile time.

    Now, here's where the static keyword starts to make sense: the word "static" is an antonym for "dynamic". So the reason why you can't override static methods is because there is no dynamic dispatching on static members - because static literally means "not dynamic". If they dispatched dynamically (and thus could be overriden) the static keyword just wouldn't make sense anymore.

提交回复
热议问题