Sub topic 3
Overriding a Method
In the last chapters you saw that a subclass gets the methods of its superclass, and that one variable can refer to objects of different classes. A subclass does not have to keep every inherited method as it is. It can replace one with its own version. This chapter shows how that works.
What Overriding Means
Overriding means a subclass writes its own version of a method that it inherits from its superclass. The new version must have the same name and the same parameter list as the old one. When you call that method on an object of the subclass, Java runs the subclass's version instead of the inherited one.
Here are some words you will see often:
- A superclass is the class being extended. It is also called the parent class.
- A subclass is the class that uses
extends. It is also called the child class. - A method signature is the method's name plus its parameter types, in order. For example,
sound()andmove(int)are signatures. - An implementation is the body of a method, which is the code inside the curly braces.
To override a method, the subclass keeps the signature and changes the implementation.
Why Overriding Matters
Picture a program about animals. Every animal can make a sound, but each kind of animal sounds different. You could write a separate method for each animal, like dogSound() and catSound(). Then any code that uses animals would have to check which kind it has and pick the matching method. That gets messy fast.
Overriding gives you a cleaner way. The superclass says "every animal has a sound() method." Each subclass then says "here is what sound() means for me." Code that uses animals calls sound() and gets the right answer for each one.
A Worked Example
Save this program as Main.java. It holds four classes in one file, which Java allows as long as only one class is public.
class Animal {
String sound() {
return "...";
}
}
class Dog extends Animal {
@Override
String sound() {
return "Woof";
}
}
class Cat extends Animal {
@Override
String sound() {
return "Meow";
}
}
public class Main {
public static void main(String[] args) {
Animal[] animals = { new Dog(), new Cat(), new Animal() };
for (Animal a : animals) {
System.out.println(a.sound());
}
}
}Compile and run it:
javac Main.java
java MainThe output is:
Woof
Meow
...Reading the Example Step by Step
Animalhas a methodsound()that returns"...". This is the default version.Dog extends Animal, soDoginheritssound(). ThenDogwrites its ownsound()with the same name and no parameters. This replaces the inherited version forDogobjects.Catdoes the same thing and returns"Meow".- In
main, the array has the typeAnimal[]. Each slot can hold anAnimalor any subclass ofAnimal. - The loop calls
a.sound()on each object. The variableahas the declared typeAnimal, but Java runs the version that belongs to the object's real class.
The line @Override above each new method is an annotation. An annotation is a label that gives the compiler extra information. This one says "I mean to override an inherited method." The next chapter covers it in detail. For now, put it on every method you override.
Seeing the Structure
Each subclass lists sound() again in the diagram because each one has its own version. If a subclass did not list it, the subclass would simply use the one it inherited.
What Gets Replaced, and What Stays
When you override a method, only that one method changes. Everything else the subclass inherits stays the same. The following program shows this.
class Vehicle {
String name() {
return "vehicle";
}
String wheels() {
return "4 wheels";
}
String describe() {
return "A " + name() + " with " + wheels();
}
}
class Bike extends Vehicle {
@Override
String name() {
return "bike";
}
@Override
String wheels() {
return "2 wheels";
}
}
class Truck extends Vehicle {
@Override
String name() {
return "truck";
}
}
public class Main {
public static void main(String[] args) {
System.out.println(new Vehicle().describe());
System.out.println(new Bike().describe());
System.out.println(new Truck().describe());
}
}The output is:
A vehicle with 4 wheels
A bike with 2 wheels
A truck with 4 wheelsNotice these points:
Bikeoverridesname()andwheels(). It does not overridedescribe(), so it inherits that method.describe()lives inVehicle, yet when it callsname()on aBike, theBikeversion runs. The overriding version is used even when the call comes from code in the superclass.Truckoverrides onlyname(). It keeps the inheritedwheels(), so it reports 4 wheels.
Overriding Through Several Levels
A class can extend a class that itself extends another class. Overriding works at every level. Each class uses the closest version above it, or its own if it has one.
class Animal {
String sound() {
return "...";
}
}
class Dog extends Animal {
@Override
String sound() {
return "Woof";
}
}
class Puppy extends Dog {
}
class Husky extends Dog {
@Override
String sound() {
return "Awoo";
}
}
public class Main {
public static void main(String[] args) {
System.out.println(new Puppy().sound()); // Woof
System.out.println(new Husky().sound()); // Awoo
}
}Puppy has no sound() of its own, so it uses the one from Dog, its direct parent. Java never skips up to Animal while Dog has a version. Husky writes its own, so it uses that.
| Class | Has its own `sound()`? | Version that runs | Result |
|---|---|---|---|
| Animal | Yes | Animal | `...` |
| Dog | Yes | Dog | `Woof` |
| Puppy | No | Dog (inherited) | `Woof` |
| Husky | Yes | Husky | `Awoo` |
Edge Cases to Watch For
Same name, different parameters
If the subclass method has the same name but different parameter types, it does not override. It adds a second, separate method. This is called overloading.
class Dog extends Animal {
String sound(int times) { // new method, not an override
return "Woof ".repeat(times);
}
}This Dog now has two methods: the inherited sound() that returns "...", and the new sound(int). Calling new Dog().sound() still returns "...". A later chapter, "Overloading Is Not Overriding", covers this difference.
Sibling classes do not affect each other
Dog and Cat both extend Animal, but they are siblings. Overriding sound() in Dog has no effect on Cat or on Animal. Each class controls only its own version.
Overriding needs inheritance
A method can only override a method that the class inherits. Two unrelated classes that both have a sound() method are not overriding anything. They just happen to share a method name.
There are rules about the method's details
The return type, the access level (such as public), and the exceptions a method declares also matter. Some changes are allowed and some are not. The chapter "The Rules of Overriding" lists them. Until then, copy the inherited method's first line exactly and change only the body.
Summary
- Overriding replaces an inherited method's body while keeping its name and parameter list.
- The object's real class decides which version runs.
- A subclass that does not override a method inherits the nearest version above it.
- Changing the parameters creates a new method, not an override.
- Put
@Overrideon every overriding method.
Exercise
Add a class Cow that extends Animal and overrides sound() to return "Moo". Then add new Cow() to the animals array in the first example. What does the program print?
Show answer
The Cow class is: class Cow extends Animal { @Override String sound() { return "Moo"; } }. With the array { new Dog(), new Cat(), new Animal(), new Cow() }, the program prints Woof, Meow, ..., and Moo, one per line.
Exercise
In the Vehicle example, add a class Tricycle that extends Bike and overrides only wheels() to return "3 wheels". What does new Tricycle().describe() return, and why?
Show answer
It returns "A bike with 3 wheels". Tricycle inherits describe() from Vehicle and name() from Bike, which returns "bike". Its own wheels() replaces Bike's version and returns "3 wheels".
Exercise
A student writes class Dog extends Animal { String sound(String mood) { return "Woof"; } } without @Override. What does new Dog().sound() return, and is sound(String) an override?
Show answer
It returns "..." because Dog still has the inherited sound() from Animal. sound(String) has a different parameter list, so it overloads sound() and does not override it.