Pet p = new Cat(Color.BLACK);

if(Math.random() < 0.5)
    p = new Dog("Clifford", "Big Red");

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 or Dog)
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 second rule of polymorphism is: The object/instance type determines what method is actually run. The most specific method possible is run.

The variable/reference type of p is Pet.

The object/instance type is either Cat or Dog, depending on the random number generated. The condition evalutes to true with a 50% probability. See Generate random numbers with Math.random().

line 4 is an example of a polymorphic method call. toString can be called because Pet, the variable/reference type, has the method. This check is done at compile time.

The specific method that is actually called depends on the actual object/instance type when the code is run. This determination is made at run time. If the object is of type Cat, line 4 runs the Pet toString method, since Cat doesn’t override toString. If the object is of type Dog, line 4 runs the Dog toString method.

The remaining lines behave the same as in the inheritance exercise. line 2 and line 3 are compile time errors. line 1 runs the Pet getName method since no other class overrides getName.

Back to Inheritance and polymorphism

Comments

Comment on Inheritance & polymorphism