What are the rules a method must follow to override a parent method in Java?
There are six rules, and most of them are about the signature having to match exactly.
public class Main {
public static void main(String[] args) {
Animal a = new Dog();
System.out.println(a.speak());
}
}
And here is the parent and the child.
public class Animal {
public String speak() {
return "...";
}
}
public class Dog extends Animal {
@Override
public String speak() {
return "woof";
}
}
So here are the rules.
the rule what it means
----------------------------- --------------------------------------------
the name is the same exactly the same name
the parameters are the same the same number and the same types
the return type is the same or a subtype of the parent's
the access can be wider public can become protected, but not
the other way round
the exceptions can be fewer the child can throw less, not more
the method is not static a static method is hidden, not
overridden
And there is one rule about the access level that is worth explaining, because it is about substitutability. If the parent method is public and the child makes it protected, then the code that holds the child as the parent type can no longer call it. So the child has broken the promise that the parent made.
And the rule about the exceptions is the same idea. If the parent says it throws a checked exception and the child says it throws a wider set, then the code that catches the parent's exception is not prepared for the extra ones, so the program breaks when the child throws them.
And there is one more rule that is not in the list, and it is the one that surprises people. A method can only be overridden if it is visible. So a private method in the parent is not inherited in any way that you can override, and a method in the parent that is package-private can only be overridden by a child in the same package.
the parent's method can the child override it?
-------------------- ---------------------------------
public yes
protected yes
package-private only in the same package
private no
static no, it is hidden instead
final no, it is not allowed at all
And there is one more thing worth knowing about, and it is that you can override a method that the parent inherited from its own parent. So if Dog extends Animal and Animal got speak from a grandparent, then Dog can still override it.
So the rule to remember is this. The signature has to match, and the child can only make the promises narrower, never wider.
The next two questions in this topic are about the three names and about the exception rule.