Static methods cannot be overridden but can be redefined in child Class
class Animal { static void doStuff() { System.out.print("animal"); } } class Dog extends Animal { // it's a redefinition // not an override static void doStuff() { System.out.print("dog"); } public static void main(String [] args) { Animal [] a = {new Animal(), new Dog(), new Animal()}; for(int x = 0; x < a.length; x++) a[x].doStuff(); // invoke the static method } }
Output
animal animal animal
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.