Pet[] pets = new Pet[2];
pets[0] = new Cat(Color.ORANGE);
pets[1] = new Dog("Snoopy", "Beagle");
System.out.println(pets[0].getName()); // line 1 (Pet)
System.out.println(pets[0].getColor()); // line 2 (error)
System.out.println(pets[1].getBreed()); // line 3 (error)
System.out.println(pets[0].toString()); // line 4 (Pet)
System.out.println(pets[1].toString()); // line 5 (Dog)
The first rule of polymorphism is: The variable/reference type determines what methods can be run.
The second rule of polymorphism is: The object/instance type determines what method is actually run. The most specific method possible is run.
An array of objects is actually an array of references. (See enhanced for loops for examples.) The type of the array variable is the reference type.
line 1
compiles without error and runs the getName
method from Pet
.
line 2
is a compile time error because getColor
is not in Pet
.
line 3
is a compile time error because getBreed
is not in Pet
.
line 4
compiles without error and runs the toString
method from Pet
, since Cat
does not override toString
.
line 5
compiles without error and runs the toString
method from Dog
.
Back to Inheritance and polymorphism