What are the rules for overriding a method in Java, and which of them does the compiler enforce?
There are five rules, and the compiler checks all of them for you.
The first rule is about the name and the parameters. The overriding method must have the same name and the same parameter list. That is what makes it an override rather than an overload.
The second rule is about the return type. The return type must be the same as the parent's, or a type that the parent's can be used as. A child that returns a String may override a method whose return type is Object, because a String can be used wherever an Object is expected.
The third rule is about the access level. The overriding method must be at least as visible as the one it overrides. You may make it more visible, so you can turn a protected method into a public one, but you may not make it less visible, so you cannot turn a public method into a private one.
The fourth rule is about the exceptions. The overriding method may throw fewer checked exceptions than the parent, or exceptions that are subclasses of the ones the parent throws. It may not throw new checked exceptions that the parent did not allow.
The fifth rule is about what can be overridden at all. A private method cannot be overridden, because a subclass cannot even see it. A static method is hidden rather than overridden. A final method cannot be overridden, and the compiler says so. And a constructor is not inherited, so it cannot be overridden either.
public class Main {
public static void main(String[] args) {
Animal animal = new Dog();
System.out.println("sound : " + animal.speak());
System.out.println("name : " + animal.getName());
System.out.println("legs : " + animal.getLegs());
}
}
class Animal {
protected String name = "animal";
// The child may widen the access, because public is more visible
// than protected.
public String getName() {
return this.name;
}
// The child may not narrow it, so this one is not allowed:
// protected String getLegs() { return "4"; }
String getLegs() {
return "4";
}
String speak() {
return "...";
}
}
class Dog extends Animal {
@Override
String speak() {
return "woof";
}
}
The next question in this topic looks closely at the return type rule and at the exception rule.