Pet p = new Cat(Color.BLACK);
System.out.println(p.getName()); // line 1 (Pet)
System.out.println(p.getBreed()); // line 2 (error)
System.out.println(p.getColor()); // line 3 (error)
System.out.println(p.toString()); // line 4 (Pet)
System.out.println(p); // line 5 (same as line 4)
The first rule of polymorphism is: The variable/reference type determines what methods can be run.
The variable/reference type of p is Pet.
line 2 and line 3 do not compile because getBreed and getColor are not in Pet. It doesn’t matter that getColor is in Cat. The method cannot be run.
line 1 runs getName from Pet. line 4 runs toString from Pet.
line 5 is the same as line 4. Printing an object automatically runs the object’s toString method.
Back to Inheritance and polymorphism