Sub topic 10
Check Override Rules with @Override
In the last few chapters you wrote subclasses that replace a method from their superclass. This chapter is about the rules Java enforces when you do that, and about the @Override annotation. @Override asks the compiler to check your work. It is one of the cheapest ways to avoid a whole class of bugs.
This chapter assumes you know how to write a subclass with extends, how to override a method, and the basic access modifiers (public, protected, package-private, private).
What @Override Does
An annotation is a label that you attach to code. It starts with @. Some annotations give information to the compiler. @Override is one of them.
When you put @Override above a method, you tell the compiler: "This method is meant to replace a method from a superclass or an interface. Check that it really does."
If the method does not override anything, the compiler stops with an error. Without the annotation, the compiler would accept the code and treat your method as a brand new method.
Here is the bug that the annotation prevents:
class Animal {
String speak() {
return "some sound";
}
}
class Cat extends Animal {
// Typo: "Speak" instead of "speak"
String Speak() {
return "meow";
}
}
public class Main {
public static void main(String[] args) {
Animal pet = new Cat();
System.out.println(pet.speak());
}
}This program compiles and prints some sound. You expected meow. Java is case sensitive, so Speak and speak are different names. Cat now has two methods: the inherited speak and a new Speak. Nothing was overridden, and nothing warned you.
Now add the annotation:
class Cat extends Animal {
@Override
String Speak() {
return "meow";
}
}The compiler now reports an error similar to this:
error: method does not override or implement a method from a supertypeYou find the typo at compile time instead of during testing, or in front of a user.
The Rules for a Valid Override
The compiler uses a fixed set of rules to decide whether a method overrides another one. If any rule is broken, you get a compile error. These rules are why @Override can catch mistakes.
Rule 1: Same name and same parameters
The overriding method must have the same name and the same parameter types, in the same order. The name plus the parameter types is called the method signature. The return type is not part of the signature.
A different parameter list gives you an overload, not an override. An overload is a second method with the same name but different parameters. Overloading is covered in a later chapter. For now, remember that @Override will reject it:
class Printer {
void print(String text) {
System.out.println(text);
}
}
class FancyPrinter extends Printer {
// Different parameter type: this is an overload, not an override
@Override
void print(int number) { // compile error
System.out.println("#" + number);
}
}Without @Override, this code compiles. FancyPrinter would have two print methods, and a call such as print("hi") would still use the superclass version.
Rule 2: The access cannot be narrower
The overriding method may be equally accessible or more accessible than the original. It may never be less accessible. From the least to the most accessible, the levels are:
private- package-private (no keyword)
protectedpublic
| Superclass method | Allowed in the subclass |
|---|---|
| `public` | `public` only |
| `protected` | `protected` or `public` |
| package-private | package-private, `protected`, or `public` |
| `private` | Not overridable (see below) |
The reason is simple. Code that holds an Animal reference may call any public method of Animal. If a subclass could make that method protected, the same call would fail for some objects. The rule keeps every subclass usable wherever the superclass is used.
class Vehicle {
public void start() {
System.out.println("Starting");
}
}
class Car extends Vehicle {
@Override
void start() { // compile error: attempting to assign weaker access privileges
System.out.println("Car starting");
}
}The fix is to write public void start() in Car.
Rule 3: Return types must be compatible
If the original method returns a primitive type such as int or boolean, or returns void, the overriding method must return exactly the same type.
If the original method returns a class type, the overriding method may return that class or any subclass of it. This is called a covariant return type.
class Animal {
Animal reproduce() {
return new Animal();
}
}
class Dog extends Animal {
@Override
Dog reproduce() { // allowed: Dog is a subclass of Animal
return new Dog();
}
}The reverse is not allowed. A subclass cannot widen the return type to a superclass of the original type.
Rule 4: Checked exceptions cannot be widened
An exception is an object that represents an error during a program run. A checked exception is one that the compiler forces you to handle or declare with throws. IOException is a common example.
An overriding method may declare the same checked exceptions as the original, fewer of them, or more specific ones. It may not declare a new or broader checked exception. It may always throw unchecked exceptions such as IllegalArgumentException.
import java.io.IOException;
class Reader {
void load() throws IOException {
System.out.println("Loading");
}
}
class SafeReader extends Reader {
@Override
void load() { // allowed: declares fewer exceptions
System.out.println("Loading safely");
}
}Again, the reason is that callers rely on the superclass contract. A caller of Reader.load() handles IOException. It has no code ready for some other checked exception.
Rule 5: Instance methods only
Only instance methods can be overridden. These cases do not count:
- A
privatemethod is not inherited, so a subclass cannot override it. A subclass method with the same name is a separate, unrelated method. - A
staticmethod belongs to the class, not to an object. A subclass method with the same name hides the original instead of overriding it. - A
finalmethod cannot be overridden at all. Thefinalkeyword is covered in a later chapter.
Adding @Override to a method in any of these situations produces a compile error. That is useful: it tells you that your idea of the code does not match what Java does.
class Base {
private void secret() { }
static void info() { }
}
class Child extends Base {
@Override
private void secret() { } // compile error: nothing to override
@Override
static void info() { } // compile error: static methods are not overridden
}Summary Table of the Rules
| Part of the method | Rule for the overriding method |
|---|---|
| Name | Must be identical |
| Parameter types | Must be identical |
| Access | Same or more accessible |
| Return type (primitive or `void`) | Must be identical |
| Return type (class) | Same class or a subclass |
| Checked exceptions | Same, fewer, or more specific |
| Kind of method | Must be a non-private, non-static, non-final instance method |
How the Compiler Decides
The diagram shows the checks in order. Reading it helps you work out why a particular @Override fails.
Overriding Methods from Object and Interfaces
Every class extends Object, so you can override methods such as toString(), equals(Object), and hashCode(). These are the most common places where @Override saves you.
A classic mistake is to write equals with the wrong parameter type:
class Point {
int x;
int y;
Point(int x, int y) {
this.x = x;
this.y = y;
}
// Wrong: the parameter is Point, not Object. This is an overload.
public boolean equals(Point other) {
return x == other.x && y == other.y;
}
}This compiles, but it does not replace Object.equals(Object). Collections and many other classes call equals(Object), so they will not use your method. With @Override the compiler would reject it, and you would fix it:
class Point {
int x;
int y;
Point(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public boolean equals(Object other) {
if (!(other instanceof Point)) {
return false;
}
Point p = (Point) other;
return x == p.x && y == p.y;
}
@Override
public int hashCode() {
return 31 * x + y;
}
}@Override also works when you implement an interface method. Interface methods are public, so your implementation must be declared public. Forgetting that is a common error, and it falls under Rule 2.
interface Greeter {
String greet();
}
class EnglishGreeter implements Greeter {
@Override
public String greet() { // "public" is required here
return "Hello";
}
}Common Mistakes
- Leaving out
@Override. The code works until a typo or a parameter mismatch turns the override into a new method. Add the annotation every time. - Adding
@Overrideto fix a compile error. The annotation does not change what the code does. It only reports problems. If it fails, correct the method signature. - Weaker access. Writing
void toString()instead ofpublic String toString()fails, becauseObject.toString()ispublic. - Expecting
staticmethods to behave like overrides. The method that runs depends on the reference type, not on the object. Use instance methods when you want polymorphism. - Changing a parameter type "slightly".
ListandArrayListare different types. A method with the other type is an overload.
Exercises
Exercise
This code does not print "Woof". Name the problem, then show how adding @Override would have revealed it. class Dog extends Animal { String speek() { return "Woof"; } }
Show answer
The method is named speek, not speak, so it does not override Animal.speak(). It is a new method, and calls to speak() still run the Animal version. If you write @Override above speek(), the compiler reports "method does not override or implement a method from a supertype", and you can correct the spelling.
Exercise
A superclass declares "public String describe()". A subclass declares "@Override String describe()" with no access keyword. Does it compile? Explain why.
Show answer
No. The subclass method is package-private, which is less accessible than public. An override may not narrow access, so the compiler reports an error about weaker access privileges. The fix is to declare it "public String describe()".
Exercise
A superclass method is declared "Number value()". Which of these overriding return types are allowed: Number, Integer, Object, or int?
Show answer
Number and Integer are allowed. Integer is a subclass of Number, so it is a covariant return type. Object is a wider type, and int is a primitive, so neither is allowed.