Task 1 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 — replacing an inherited method

Lesson

Giving a subclass its own version

A subclass can override an inherited method: define a method with the same signature (same name and parameters). Then, when that method is called on a subclass object, the subclass's version runs instead of the superclass's. Mark it with @Override — the compiler checks that you really are overriding an inherited method.


Worked example

class Dog extends Animal {
    @Override
    public String describe() {   // same signature as Animal's describe()
        return getName() + " is a dog";
    }
}

Animal a = new Animal("Generic");
Dog d = new Dog("Rex");
System.out.println(a.describe());   // "Generic is an animal"
System.out.println(d.describe());   // "Rex is a dog" — Dog's version

Same method name, different result: the object's actual class decides which version runs.


▶ Try it: run this — describe() gives one answer for an Animal and another for a Dog.



To override a method, the subclass defines a method with...


When describe() is called on a Dog object, Java runs...


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 n+" is a dog";} }
public class Main { public static void main(String[] a){
    System.out.println(new Animal("Gen").describe());
    System.out.println(new Dog("Rex").describe());
}}

@Override tells the compiler that...


True or false?