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.4 Polymorphism — a superclass reference

Lesson

One variable, many object types

A variable of a superclass type can hold a subclass object: Animal a = new Dog("Rex");. The declared type is Animal, but the actual object is a Dog. When you call an overridden method, Java runs the actual object's version — this is dynamic dispatch (polymorphism). So a.describe() runs Dog's version even though a is typed as Animal.


Worked example

Animal a = new Dog("Rex");   // declared Animal, actual Dog
System.out.println(a.describe());   // "Rex is a dog" — Dog's version runs

The variable's type does not decide which overridden method runs — the real object does.


▶ Try it: run this — through Animal variables, each object still uses its own describe().



Can a variable of type Animal hold a Dog object?


For Animal a = new Dog("Rex"), a.describe() 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){
    Animal x = new Dog("Sam");
    System.out.println(x.describe());
}}

Running the actual object's version of a method is called...


True or false?