Sub topic 4
Letting the Compiler Check You with @Override
In the last chapter you learned how a subclass can override a method. Overriding only works when the method in the subclass matches the method in the superclass. If the name or the parameters differ even slightly, Java does not override anything. It quietly creates a separate, new method instead.
This chapter shows you a small tool that catches those mistakes for you: the @Override annotation.
The Problem: Mistakes That Compile Fine
Here is a Dog class that is meant to override sound(). Look closely at the method name.
class Animal {
String sound() {
return "...";
}
}
class Dog extends Animal {
String sond() { // typo: "sond" instead of "sound"
return "Woof";
}
}
public class Main {
public static void main(String[] args) {
Animal a = new Dog();
System.out.println(a.sound());
}
}This program compiles with no errors. When you run it, it prints:
...You expected Woof. The typo means Dog never overrode sound(). It added a brand-new method called sond() that nobody calls. When the program asks for sound(), Java finds only the one inherited from Animal.
The compiler, which is the program that turns your Java code into something the computer can run, did not complain. From its point of view, adding a new method called sond() is perfectly legal. The bug only shows up later, as wrong output, and you have to hunt for it.
What an Annotation Is
An annotation is a label you attach to a piece of code, such as a class or a method. It starts with the @ symbol. Annotations give extra information to the compiler or to other tools. They do not change what your code does when it runs.
@Override is an annotation built into Java. You put it on the line just above a method. It tells the compiler: "I mean for this method to override a method from a parent type. Please check that it really does."
The Fix: Add @Override
Here is the same Dog class with the annotation added:
class Dog extends Animal {
@Override
String sond() {
return "Woof";
}
}Now the program does not compile. The compiler stops with an error like this:
Main.java:8: error: method does not override or implement a method from a supertype
@Override
^
1 errorA supertype is any class or interface that your class inherits from. The error says the compiler looked in Animal (and in Object, which every class inherits from) and found no method named sond() with no parameters. So your claim of overriding is false, and it tells you right away.
You fix the typo:
class Dog extends Animal {
@Override
String sound() {
return "Woof";
}
}The program compiles and prints Woof.
How the Compiler Checks
When the compiler sees @Override on a method, it searches the class's supertypes for a method with the same name and the same parameter types. The steps look like this:
The signature of a method is its name plus the list of its parameter types. The return type is not part of the signature. @Override checks that your method's signature matches one you inherited.
Mistakes @Override Catches
A typo in the name is the most obvious mistake. There are several others.
Wrong Capitalization
Java treats uppercase and lowercase letters as different. toString and tostring are two different names.
class Point {
private final int x;
private final int y;
Point(int x, int y) {
this.x = x;
this.y = y;
}
public String tostring() { // lowercase "s": does not override toString()
return "Point(" + x + ", " + y + ")";
}
}
public class Main {
public static void main(String[] args) {
System.out.println(new Point(1, 2));
}
}This prints something like Point@1b6d3586 instead of Point(1, 2). System.out.println calls toString(), and Point never overrode it. With @Override on tostring(), the compiler would reject the code. (A later chapter covers toString and its partners in detail.)
Wrong Parameter Type
The parameter types must match exactly. A parameter type that is close but not the same creates a separate method.
class Greeter {
String greet(String name) {
return "Hello, " + name;
}
}
class LoudGreeter extends Greeter {
String greet(Object name) { // Object, not String
return "HELLO, " + name + "!";
}
}
public class Main {
public static void main(String[] args) {
Greeter g = new LoudGreeter();
System.out.println(g.greet("Ana"));
}
}This prints Hello, Ana. LoudGreeter now has two greet methods, one taking String and one taking Object. Having two methods with the same name but different parameters is called overloading, and a later chapter explains why it behaves differently from overriding. Adding @Override to greet(Object name) turns this silent bug into a compile error.
The Superclass Changes Later
This mistake is sneaky because your code was correct when you wrote it. Suppose a teammate renames a method in the superclass:
class Animal {
String makeSound() { // was called sound() before
return "...";
}
}
class Dog extends Animal {
@Override
String sound() { // now an error, which is what you want
return "Woof";
}
}Without @Override, Dog.sound() would quietly become an ordinary method that nothing calls, and every dog would print .... With @Override, the build fails as soon as the rename happens. The error tells your team exactly which subclasses need updating.
Summary of Mistakes
| Mistake | Without @Override | With @Override |
|---|---|---|
| Typo in name (`sond`) | Compiles, wrong method runs | Compile error |
| Wrong capitalization (`tostring`) | Compiles, wrong method runs | Compile error |
| Wrong parameter type (`Object` instead of `String`) | Compiles, creates an overload | Compile error |
| Superclass method renamed or removed | Compiles, override silently lost | Compile error |
| Correct override | Works | Works |
@Override Works with Interfaces Too
An interface is a type that lists methods a class promises to provide. A later chapter covers interfaces fully. For now, know that @Override works on methods that implement an interface method, too.
interface Greeting {
String text();
}
class Morning implements Greeting {
@Override
public String text() {
return "Good morning";
}
}
public class Main {
public static void main(String[] args) {
Greeting g = new Morning();
System.out.println(g.text());
}
}This prints Good morning. If you misspelled text as txt, the compiler would report the same "does not override or implement" error. Here it would also complain that Morning does not provide text().
What @Override Does Not Do
Be clear about the limits of this annotation:
- It does not make a method override. The match between signatures does that.
@Overrideonly checks the match. - It does not change how the program runs. Remove it from a correct override and the program behaves the same.
- It is not required. Java accepts overrides without it. That is why the mistakes above compile when it is missing.
- It cannot be used on a method that has no parent version to override, such as a brand-new method or a
staticmethod. Putting it there is a compile error.
Exercises
Exercise
A class Cat extends Animal and defines String Sound() { return "Meow"; } with a capital S, with no @Override. Calling sound() on a Cat through an Animal variable prints "...". Why, and what would adding @Override do?
Show answer
Java names are case-sensitive, so Sound() is a new method, not an override of sound(). The inherited Animal.sound() runs and returns "...". Adding @Override above Sound() makes the compiler report "method does not override or implement a method from a supertype", which shows you the mistake right away.
Exercise
You add @Override to a method and the program compiles. You then remove @Override and recompile. Does the program's output change?
Show answer
No. @Override only asks the compiler to check that the method overrides something. It does not change what the program does at runtime, so a correct override behaves the same with or without it.
Exercise
Class Shape has double area(). Class Square extends Shape and defines @Override double area(int scale). Will this compile? Explain.
Show answer
No. The parameter list (int scale) differs from Shape's area(), which takes no parameters, so the signatures do not match. Without @Override this would compile as a separate overloaded method. With @Override the compiler reports an error because no supertype has an area(int) method.