I'm actually pretty happy with the docs here (thanks @baao): https://docs.oracle.com/javase/tutorial/java/IandI/override.html.
Note the difference between hiding and overriding:
- Hiding refers to a static method in a subclass with the same signature as the static method in the superclass and is considered bad practice
- Overriding is what allows subclasses to modify inherited behavior, and is not bad practice.
I'll use the example again from the docs:
public class Animal {
public static void testClassMethod() {
System.out.println("The static method in Animal");
}
public void testInstanceMethod() {
System.out.println("The instance method in Animal");
}
}
public class Cat extends Animal {
public static void testClassMethod() {
System.out.println("The static method in Cat");
}
public void testInstanceMethod() {
System.out.println("The instance method in Cat");
}
public static void main(String[] args) {
Cat myCat = new Cat();
Animal myAnimal = myCat;
myAnimal.testClassMethod();
// "The static method in Animal"
myAnimal.testInstanceMethod();
// "The instance method in Cat"
}
}
To quote another answer as well from What is method hiding in Java? Even the JavaDoc explanation is confusing:
"Calling static methods on instances rather than classes is a very bad practice, and should never be done."