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.
Animal a = new Dog("Rex");
Animal
Dog
a.describe()
a
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().
describe()
Can a variable of type Animal hold a Dog object?
For Animal a = new Dog("Rex"), a.describe() runs...
Animal a = new Dog("Rex")
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?