Sub topic 3
Override Superclass Methods
A subclass is a class that gets behavior from another class. The class it gets behavior from is the superclass. In Java, you connect them with the word extends.
Overriding means a subclass writes its own version of a method that the superclass already has. The new version replaces the old one, but only for objects of the subclass.
Why Override a Method?
Sometimes an inherited method is almost right. A dog should speak differently than a general animal. Overriding lets you change that one behavior and keep the rest of the class as it is.
A Worked Example
class Animal {
String speak() {
return "The animal makes a sound";
}
}
class Dog extends Animal {
@Override
String speak() {
return "The dog barks";
}
}
class Cat extends Animal {
@Override
String speak() {
return "The cat meows";
}
}
public class Main {
public static void main(String[] args) {
Animal a = new Animal();
Animal d = new Dog();
Animal c = new Cat();
System.out.println(a.speak());
System.out.println(d.speak());
System.out.println(c.speak());
}
}The program prints:
The animal makes a sound
The dog barks
The cat meowsLook at the variable d. Its type is Animal, but the object it holds is a Dog. Java picks the method based on the real object at run time. This is called dynamic dispatch. You will study it more in the next chapter.
The @Override Label
@Override is an annotation. An annotation is a note that starts with @. This note tells the compiler, the tool that checks your code, "I mean to replace a method from the superclass."
If the name or parameters do not match, the compiler reports an error. This catches typing mistakes early.
Rules for Overriding
| Rule | What it means |
|---|---|
| Same name | The method name must match exactly. |
| Same parameters | The inputs must match in number and type. |
| Same return type | The method must return the same kind of value. |
| No narrower access | If the original is `public`, the new version must be `public` too. |
You can still call the original method from inside the new one with super.speak(). You will learn how in the chapter on the super keyword.
Exercise
In the Dog class, you write @Override String Speak() with a capital S. What happens when you compile?
Show answer
The compiler reports an error. "Speak" is not the same name as "speak", so Dog does not override anything. The @Override label makes the compiler point out the mistake.