Sub topic 6
Extending Behavior with super
When a subclass overrides a method, its new version replaces the old one. Sometimes you don't want to replace the old behavior completely. You want to keep it and add a little more. Java gives you the super keyword for this.
This chapter shows how to call the parent's version of a method from inside the child's version. It also covers the mistakes beginners often make with super.
What super Means
super is a keyword that points to the parent class's version of a member. The parent class is also called the superclass. If you write super.describe() inside a subclass, Java runs the superclass's describe() method. It does not run the subclass's own version.
Compare it with this:
this.describe()means "rundescribe()on this object." Java uses the object's real class, so you get the subclass version.super.describe()means "run thedescribe()my parent class defines." You get the parent's version.
A First Example
A bank has a basic Account class. A SavingsAccount should describe itself the same way, but with a note added at the end.
class Account {
String describe() {
return "Account";
}
}
class SavingsAccount extends Account {
@Override
String describe() {
return super.describe() + " (savings)";
}
}
public class Main {
public static void main(String[] args) {
Account a = new SavingsAccount();
System.out.println(a.describe());
}
}Output:
Account (savings)Here is what happens, step by step:
- The variable
aholds aSavingsAccountobject, so Java runsSavingsAccount.describe(). - That method calls
super.describe(), which runsAccount.describe()and gets back"Account". - The child adds
" (savings)"and returns the result.
The child did not copy the parent's code. It reused that code. If the bank later changes Account.describe(), the savings account picks up the change automatically.
Forgetting super: A Common Bug
Beginners sometimes leave out super and write the method name alone. The method then calls itself instead of the parent.
class Account {
String describe() {
return "Account";
}
}
class SavingsAccount extends Account {
@Override
String describe() {
return describe() + " (savings)"; // bug: calls itself
}
}
public class Main {
public static void main(String[] args) {
System.out.println(new SavingsAccount().describe());
}
}This compiles, but it crashes when it runs. describe() with no prefix means this.describe(), and the object is a SavingsAccount. So the method calls itself, which calls itself again, without end. Java stops it with a StackOverflowError. A stack overflow happens when a program runs out of the memory it uses to track method calls.
Before or After: Where to Put the super Call
You can call super at the start, at the end, or in the middle of your method. Where you put it decides the order things happen.
class Robot {
void greet() {
System.out.println("Hello.");
}
}
class PoliteRobot extends Robot {
@Override
void greet() {
System.out.println("Excuse me.");
super.greet();
System.out.println("Have a nice day.");
}
}
public class Main {
public static void main(String[] args) {
Robot r = new PoliteRobot();
r.greet();
}
}Output:
Excuse me.
Hello.
Have a nice day.| Where you call super | Effect | Typical use |
|---|---|---|
| First line | Parent's work happens first, then yours | Setup steps, adding text to the end |
| Last line | Your work happens first, then the parent's | Checking input before the parent acts |
| Middle | Your work wraps around the parent's | Logging before and after |
| Not at all | Parent's version is fully replaced | The old behavior is wrong for this class |
Chains of super Calls
super always means the class directly above. It does not jump to the top of the family tree. If each level calls super, the calls form a chain that climbs one step at a time.
class Vehicle {
String start() {
return "check fuel";
}
}
class Car extends Vehicle {
@Override
String start() {
return super.start() + ", fasten seatbelt";
}
}
class SportsCar extends Car {
@Override
String start() {
return super.start() + ", warm up engine";
}
}
public class Main {
public static void main(String[] args) {
Vehicle v = new SportsCar();
System.out.println(v.start());
}
}Output:
check fuel, fasten seatbelt, warm up engineSportsCar.start() calls Car.start(), which calls Vehicle.start(). Each level adds its own step on the way back.
You cannot skip a level
Java has no super.super. Writing super.super.start() inside SportsCar is a compile error. If SportsCar needs only the Vehicle behavior, the class design probably needs rethinking. A good fix is to move that behavior into its own method in Vehicle, so any subclass can call it by name.
An Edge Case: super Inside Calls Can Still Dispatch
super.describe() picks the parent's version of describe() and nothing else. If the parent's method calls other methods, those calls follow the normal rule and use the object's real class.
class Account {
String name() {
return "Account";
}
String describe() {
return "This is " + name();
}
}
class SavingsAccount extends Account {
@Override
String name() {
return "Savings";
}
@Override
String describe() {
return super.describe() + "!";
}
}
public class Main {
public static void main(String[] args) {
System.out.println(new SavingsAccount().describe());
}
}Output:
This is Savings!super.describe() runs Account.describe(). Inside it, name() means this.name(). The object is still a SavingsAccount, so SavingsAccount.name() runs. super changes which describe() runs. It does not turn the object into an Account.
Rules and Limits of super
- Only in instance methods and constructors. A
staticmethod belongs to the class, not to an object, so it has nosuper. Usingsuperthere is a compile error. - Only visible members. You cannot call a parent's
privatemethod throughsuper, because the child cannot see it. - Not only in the overriding method. Any instance method in the child can call
super.someMethod(). In practice, you mostly use it inside the override of the same method. - Not for abstract methods. If the parent method has no body, there is nothing to call. (Abstract methods come later in this tutorial.)
super.method() versus super(...)
super has a second use you may have seen with constructors. A constructor is the special method that sets up a new object. These two forms look alike but do different jobs.
| Form | Where it goes | What it does |
|---|---|---|
| `super.method()` | Inside any instance method or constructor | Runs the parent's version of a method |
| `super(args)` | First statement of a constructor only | Runs a parent constructor to set up the parent's part of the object |
Summary
super.method()runs the parent class's version of a method, even when the object's class overrides it.- Use it to add to inherited behavior instead of copying it.
- Leaving out
superin an override usually causes endless self-calls and aStackOverflowError. superclimbs exactly one level, andsuper.superdoes not exist.- Inside the parent's code, other method calls still use the object's real class.
Exercise
A class Pizza has a method toppings() that returns "cheese". A subclass PepperoniPizza overrides toppings(). Write the override so that new PepperoniPizza().toppings() returns "cheese, pepperoni" without typing the word "cheese" in PepperoniPizza.
Show answer
Call the parent's version and add to it: @Override String toppings() { return super.toppings() + ", pepperoni"; }. super.toppings() returns "cheese" from Pizza, and the override appends ", pepperoni".
Exercise
In the Vehicle, Car, SportsCar example, suppose Car.start() is changed to return "fasten seatbelt" and no longer calls super.start(). What does new SportsCar().start() return now?
Show answer
It returns "fasten seatbelt, warm up engine". SportsCar still calls super.start(), which runs Car.start(). Car no longer calls Vehicle.start(), so the chain stops there and "check fuel" never appears.
Exercise
A subclass override is written as: @Override void save() { System.out.println("Saving child"); save(); }. What happens when save() is called, and how do you fix it so the parent's save() also runs?
Show answer
The program keeps calling the child's save() on itself until it crashes with a StackOverflowError, because save() with no prefix means this.save(). The fix is to write super.save() instead of save(), so the parent's version runs once after the message prints.
Exercise
In the Account and SavingsAccount example with name() and describe(), what would new SavingsAccount().describe() return if SavingsAccount did not override name()?
Show answer
It would return "This is Account!". Account.describe() calls name(), and with no override in SavingsAccount, the inherited Account.name() runs and returns "Account". SavingsAccount.describe() then adds "!".