Sub topic 7
The Rules of Overriding
In the last few chapters you wrote methods in a subclass that replaced methods from a superclass. Java lets you do that, but only when you follow a short list of rules. The compiler checks these rules for you. This chapter explains each rule, shows code that follows it, and describes the errors you get when code breaks it.
A few terms first:
- A superclass is the class you extend. A subclass is the class that extends it.
- A method signature is the method's name plus the types of its parameters, in order. The return type and the parameter names are not part of it.
- To override a method is to write a method in a subclass that replaces an inherited method with the same signature.
Why Rules Are Needed
Polymorphism depends on a promise. When you write Shape s = new Circle();, the compiler checks every call on s against the Shape class. At runtime, Java may run the Circle version instead. That only works if the Circle version can safely stand in for the Shape version.
Every rule below protects that promise. The question behind each one is: "Can code that only knows about the superclass still call this method safely?"
Rule 1: The Signature Must Match
The overriding method must have the same name and the same parameter types, in the same order. Parameter names can differ.
| Superclass method | Subclass method | Result |
|---|---|---|
| `void greet(String name)` | `void greet(String who)` | Override. Only the names differ. |
| `void greet(String name)` | `void greet(Object name)` | Not an override. The parameter type differs. |
| `void greet(String name)` | `void greet(String name, int times)` | Not an override. The parameter count differs. |
| `void greet(String name)` | `void Greet(String name)` | Not an override. Java names are case-sensitive. |
When the signature differs, Java does not complain. It treats your method as a brand-new method that sits next to the inherited one. The program compiles, and the old method still runs through superclass references. This mistake is easy to miss, and it is why @Override matters.
Rule 2: The Return Type Must Be Compatible
For primitive types such as int, double, and boolean, and for void, the return type must be exactly the same. A superclass method returning int cannot be overridden by one returning long.
For object types the rule is looser. The overriding method may return the same type or a subtype. A subtype is a class that extends the original type, or implements it if it is an interface. This is called a covariant return type. "Covariant" means the return type gets more specific as the class gets more specific.
This is safe because a Circle is a Shape. Code that expects a Shape back is happy to get a Circle.
Rule 3: Access Can Stay the Same or Get Wider
An access modifier controls which code can call a method. From most closed to most open, Java has four levels:
| Level | Keyword | Who can call it |
|---|---|---|
| 1 (narrowest) | `private` | Only the same class |
| 2 | none (package-private) | Classes in the same package |
| 3 | `protected` | Same package, plus subclasses |
| 4 (widest) | `public` | Everyone |
An overriding method may keep the same level or move down the table to a wider one. It may never move up to a narrower one. If Shape.name() is public, a protected Circle.name() would break code that calls s.name() from another package. The compiler rejects it with an error like "attempting to assign weaker access privileges".
private methods are a special case. A subclass cannot see them, so they are never overridden at all. A later chapter covers this.
Here is a complete program that uses Rules 2 and 3:
class Shape {
protected Shape copy() {
return new Shape();
}
public String name() {
return "Shape";
}
}
class Circle extends Shape {
// Wider access (protected -> public) and a covariant return (Shape -> Circle).
@Override
public Circle copy() {
return new Circle();
}
@Override
public String name() {
return "Circle";
}
// Would not compile: narrower access than the public Shape.name()
// @Override
// protected String name() { return "Circle"; }
}
public class Main {
public static void main(String[] args) {
Circle c = new Circle();
Circle twin = c.copy(); // no cast needed, thanks to the covariant return
System.out.println(twin.name()); // Circle
Shape s = c;
Shape other = s.copy(); // declared type Shape, runtime type Circle
System.out.println(other.name()); // Circle
}
}The covariant return gives you something useful. With a Circle variable, c.copy() hands back a Circle directly. You do not have to cast the result.
Rule 4: No New or Broader Checked Exceptions
An exception is an object Java throws when something goes wrong. A checked exception, such as IOException, is one the compiler forces you to handle or declare with throws. An unchecked exception, such as IllegalArgumentException, extends RuntimeException, and the compiler does not track it.
The rule covers checked exceptions only. An overriding method may:
- throw the same checked exceptions as the superclass method,
- throw narrower ones (subclasses of the declared exceptions), or
- throw no checked exceptions at all.
It may not add a new checked exception, or a broader one such as Exception when the original declared IOException. Code that calls the method through a superclass reference has only prepared a catch for what the superclass declared. A surprise exception would get past it.
Unchecked exceptions are free. Any method may throw them.
import java.io.FileNotFoundException;
import java.io.IOException;
class Loader {
String load(String name) throws IOException {
return "loaded " + name;
}
}
class SafeLoader extends Loader {
// Allowed: declares no checked exceptions at all.
@Override
String load(String name) {
return "safely loaded " + name;
}
}
class FileLoader extends Loader {
// Allowed: FileNotFoundException is a subclass of IOException.
@Override
String load(String name) throws FileNotFoundException {
if (name.isEmpty()) {
throw new FileNotFoundException("no file name given");
}
return "file " + name;
}
// Would not compile: Exception is broader than IOException.
// @Override
// String load(String name) throws Exception { return name; }
}
public class Main {
public static void main(String[] args) {
Loader[] loaders = { new Loader(), new SafeLoader(), new FileLoader() };
for (Loader l : loaders) {
try {
System.out.println(l.load("data.txt"));
} catch (IOException e) {
System.out.println("Failed: " + e.getMessage());
}
}
}
}The output is:
loaded data.txt
safely loaded data.txt
file data.txtThe single catch (IOException e) in main covers every loader. That works only because no subclass throws anything outside IOException.
All Four Rules Together
| Part of the method | Rule for the override | Example that is allowed |
|---|---|---|
| Name and parameter types | Must match exactly | `area()` overrides `area()` |
| Return type (primitive or `void`) | Must match exactly | `int` stays `int` |
| Return type (object) | Same or a subtype | `Shape` becomes `Circle` |
| Access | Same or wider | `protected` becomes `public` |
| Checked exceptions | Same, narrower, or none | `IOException` becomes `FileNotFoundException` |
| Unchecked exceptions | No restriction | May add `IllegalStateException` |
A simple way to remember them: an override may promise more, but never less. It may return something more specific, let more callers in, and throw fewer problems. It may not take away anything the superclass promised.
Common Mistakes
- Changing a parameter type "slightly". Writing
equals(Point p)instead ofequals(Object o)creates a new method rather than an override. A later chapter looks at this case in detail. - Shrinking access by accident. Leaving off
publicwhen you override an interface method makes it package-private, which is narrower. The compiler rejects it. - Changing a primitive return type.
long count()cannot overrideint count(), even though alongcan hold anyint. - Adding
throws Exceptionto get rid of a compile error inside the method. Handle the exception inside the method, or wrap it in an unchecked exception.
Exercise
The superclass has public Number value(). Which of these subclass methods are valid overrides? (a) public Integer value() (b) protected Number value() (c) public Object value() (d) public Number value(int x)
Show answer
Only (a) is a valid override, because Integer is a subtype of Number, which makes it a covariant return. (b) narrows access from public to protected, so it does not compile. (c) returns a broader type, so it does not compile. (d) has a different parameter list, so it is a separate new method. It compiles, but it overrides nothing.
Exercise
A superclass declares void save() throws IOException. A subclass declares @Override void save() throws IllegalArgumentException. Does this compile, and why?
Show answer
Yes. IllegalArgumentException is an unchecked exception (it extends RuntimeException), and the checked-exception rule does not apply to unchecked exceptions. The override also drops IOException, which is allowed because it throws fewer checked exceptions.
Exercise
Why does Java allow an overriding method to make access wider but not narrower? Explain using a superclass reference.
Show answer
Code may call the method through a superclass reference, such as Shape s = new Circle(); s.name();. The compiler approves that call based on the access declared in Shape. If Circle could narrow the access, a call the compiler had already approved could be blocked at runtime. Widening access never blocks any call that was allowed before, so it is safe.