Why is it not possible to override static methods?
If possible, please use an example.
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.