Task 5 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.4 Polymorphism — one method, many types

Lesson

Why overriding pays off

The payoff: a method that takes a superclass parameter works with any subclass, automatically using each one's overridden behavior. You write the method once and it handles every current — and future — subclass. This is polymorphism: "many forms" through one interface.


Worked example

static void announce(Animal a) {
    System.out.println("Meet: " + a.describe());
}

announce(new Dog("Rex"));    // Meet: Rex is a dog
announce(new Cat("Felix"));  // Meet: Felix is a cat

announce takes an Animal, so it accepts a Dog, a Cat, or any other Animal — each described in its own way.


▶ Try it: run this — the same announce method handles a Dog and a Cat.



A method with an Animal parameter can be called with...


Inside announce(Animal a), calling a.describe() uses...


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";} }
class Cat extends Animal { Cat(String x){super(x);} String describe(){return n+" is a cat";} }
public class Main {
    static void show(Animal a){ System.out.println(a.describe()); }
    public static void main(String[] x){
        show(new Dog("Rex"));
        show(new Cat("Mia"));
    }
}

Polymorphism means...


True or false?