Task 3 of 7 · 0 solved · 7 to go0%
You can read the problem, but answers are checked only for signed-in students. Sign in to answer →

7.2 Overriding — calling super.method()

Lesson

Extending instead of replacing

Sometimes you want to add to the superclass's behavior rather than replace it. Inside an override, super.method() calls the superclass's version of that method. You can take its result and build on it.


Worked example

class Dog extends Animal {
    @Override
    public String describe() {
        return super.describe() + " (a dog)";   // reuse Animal's version, then add
    }
}

System.out.println(new Dog("Rex").describe());   // "Rex is an animal (a dog)"

super.describe() returns "Rex is an animal"; the override appends " (a dog)".


▶ Try it: run this — the override reuses the inherited description and extends it.



Inside an override, super.describe() calls...


If Animal's describe() returns "Rex is an animal", then super.describe() + " (a dog)" gives...


Type exactly what this program prints.

class Animal { String n; Animal(String x){n=x;} String describe(){return n+" is an animal";} }
class Dog extends Animal { Dog(String x){super(x);} String describe(){return super.describe()+" (a dog)";} }
public class Main { public static void main(String[] a){
    System.out.println(new Dog("Rex").describe());
}}

super.method() lets you...


True or false?