Sub topic 3
Override Superclass Methods
What overriding means
A subclass inherits the methods of its superclass. Sometimes an inherited method does not fit the subclass. A Dog is an Animal, but "Some sound" is a poor description of what a dog says.
Overriding means writing a method in a subclass that has the same name and the same parameter list as a method in its superclass. When you call that method on a subclass object, Java runs the subclass version instead of the inherited one.
This chapter assumes you know how to write a class, a method, and a constructor, and how to run a Java program with javac and java. It also assumes you have seen extends in the previous chapters.
A first example
Here is a superclass with one method, and two subclasses. Dog overrides the method. Cat does not.
class Animal {
String speak() {
return "Some sound";
}
}
class Dog extends Animal {
@Override
String speak() {
return "Woof";
}
}
class Cat extends Animal {
// No speak() here, so Cat uses the inherited version.
}
public class Main {
public static void main(String[] args) {
Animal animal = new Animal();
Dog dog = new Dog();
Cat cat = new Cat();
System.out.println(animal.speak());
System.out.println(dog.speak());
System.out.println(cat.speak());
}
}The program prints:
Some sound
Woof
Some soundEach object follows one rule. If its class declares the method, Java uses that version. If not, Java looks in the superclass, then in that class's superclass, and so on. Dog declares speak(), so dog.speak() prints "Woof". Cat declares nothing, so cat.speak() uses the one in Animal.
How Java finds the method to run
Java starts at the class of the object and walks up the inheritance chain. It stops at the first class that declares a matching method.
Every class has Object at the top of its chain, so the search always ends. You will meet Object in a later chapter.
What counts as the same method
A method is identified by its name and its parameter types. Together these are called the method signature. To override, the subclass method needs the same signature as the superclass method.
These are all the same signature:
String speak()andString speak()void feed(int grams)andvoid feed(int amount)
The parameter names do not matter. The parameter types and their order do.
The return type must also match for a simple override. Java allows a few more flexible cases, such as returning a more specific type. Those cases belong to the chapter on override rules, so for now use the same return type.
Use @Override every time
@Override is an annotation, a label you put above a method to tell the compiler something. It says: "This method is meant to override a superclass method."
If you add @Override and nothing in the superclass matches, the compiler gives an error. That makes it a safety net. Without it, a small typo creates a brand new method and the program still compiles.
class Animal {
String speak() {
return "Some sound";
}
}
class Dog extends Animal {
@Override
String speek() { // typo: the compiler reports an error here
return "Woof";
}
}The compiler reports that speek() does not override or implement a method from a supertype. Without @Override, this code would compile. You would then wonder why dog.speak() still prints "Some sound".
@Override is optional, but you should write it on every overriding method. The chapter on override rules covers it in more detail.
A common mistake: overloading by accident
Overloading means giving two methods the same name but different parameter lists. An overload is not an override. It is a separate method that happens to share a name.
Suppose you want Dog to bark several times and you write this:
class Animal {
String speak() {
return "Some sound";
}
}
class Dog extends Animal {
String speak(int times) { // different parameters, so a new method
return "Woof ".repeat(times).trim();
}
}
public class Main {
public static void main(String[] args) {
Dog dog = new Dog();
System.out.println(dog.speak());
System.out.println(dog.speak(2));
Animal animal = dog;
System.out.println(animal.speak());
}
}The output is:
Some sound
Woof Woof
Some soundDog now has two methods named speak: the inherited speak() and the new speak(int). The new one did not replace anything. If you had put @Override on speak(int times), the compiler would have refused to compile it and shown you the mistake right away.
The table summarizes the difference.
| Row | Overriding | Overloading |
|---|---|---|
| Where | Subclass and superclass | Same class, or across a hierarchy |
| Name | Same | Same |
| Parameters | Same | Different |
| Result | Replaces the inherited behavior | Adds another method |
The chapter on overloading and hiding returns to this topic.
Methods that cannot be overridden this way
Not every method can be overridden. Three cases are worth knowing now.
Private methods
A private method is visible only inside its own class. A subclass does not inherit it, so it has nothing to override. If a subclass declares a method with the same name, it is a completely separate method.
class A {
private String name() {
return "A";
}
String show() {
return name();
}
}
class B extends A {
String name() { // a new, unrelated method
return "B";
}
}
public class Main {
public static void main(String[] args) {
B b = new B();
System.out.println(b.show());
System.out.println(b.name());
}
}This prints:
A
BThe method show() is written in A. Inside A, the call name() refers to A's private method. B.name() is a different method, so it has no effect on show().
Static methods
A static method belongs to the class, not to an object. Declaring a static method with the same signature in a subclass does not override it. It is called hiding, and it has its own chapter.
Final methods
A method marked final cannot be overridden at all. If a subclass tries, the compiler reports an error. The chapter on abstract and final covers this.
You cannot make access weaker
The subclass method must be at least as accessible as the one it overrides. The access levels, from most open to least open, are public, protected, package-private (no keyword), and private.
If Animal.speak() is public, then Dog.speak() must also be public. Making it package-private is a compile error. Making it wider is allowed. A package-private method can be overridden by a protected or public one.
class Animal {
public String speak() {
return "Some sound";
}
}
class Dog extends Animal {
@Override
public String speak() { // must stay public
return "Woof";
}
}If you forget public here, the compiler tells you that you are attempting to assign weaker access privileges. The chapters on access rules and override rules explain why.
Overriding replaces, it does not add
When Dog overrides speak(), the Animal version is no longer run for a Dog. The subclass method fully replaces it.
Often you want to keep the superclass behavior and add to it. Java has a keyword for that, super, which lets the subclass method call the superclass version. It has its own chapter later. For now, remember that a plain override does not run the original code.
Overriding and the type of the variable
Take another look at the end of the overload example:
Animal animal = dog;
System.out.println(animal.speak());Here a variable of type Animal holds a Dog object. With a true override, Java picks the version from the object's real class, not from the variable's type. With the overload from the earlier example, nothing was overridden, so Animal's method ran.
The next chapter explains this selection, called dynamic dispatch, in detail.
Checklist for overriding a method
- Find the method in the superclass. Copy its name and parameter types exactly.
- Use the same return type.
- Use the same access level or a wider one.
- Put
@Overrideabove the method. - Make sure the method is not
private,static, orfinalin the superclass. - Compile. If the compiler complains, read the message. It usually names the exact problem.
Summary
- Overriding means a subclass writes a method with the same signature as an inherited method.
- Java runs the version found first when it searches from the object's class upward.
- Same name with different parameters is overloading, not overriding.
- Private, static, and final methods do not follow the simple override rules.
- Use
@Overrideso the compiler checks your work.
Exercise
Add a class Bird that extends Animal (whose speak() returns "Some sound") and overrides speak() to return "Tweet". What does new Bird().speak() print, and what does new Animal().speak() print?
Show answer
new Bird().speak() prints "Tweet" and new Animal().speak() prints "Some sound". Bird declares its own speak() with the same signature, so Java finds it first. The Animal object has no Bird involved, so it still uses Animal's version. The Bird method should be written as @Override String speak() { return "Tweet"; }.
Exercise
Dog extends Animal. Animal has String speak(). Dog has String speak(String sound) marked with @Override. Will this compile, and why?
Show answer
No. The compiler gives an error. speak(String sound) has a different parameter list, so it does not override speak(). Because @Override says it should, the compiler reports that the method does not override a method from a supertype. Removing @Override would make the code compile, but then speak(String) is only an overload.