Lab 8: Polymorphism

Java supports polymorphism through overriding methods.

In order to override a method, a derived class must define a method with the same signature as a method in some base class. toString() and equals(Object o) are common examples as every class in Java automatically derives from Object, which defines both of these methods with default (and usually undesirable) behavior.

The Java virtual machine (JVM) selects the appropriate method to invoke at run-time. This is called dynamic binding. The particular method to invoke is determined based on the specific type of object. This mechanism is possible through the use of references.

In this lab, you will implement the following class hierarchy:




Shape is the base abstract class. It defines a single abstract method, draw(), which the derived classes (Rectangle and Circle) will override and define. An abstract method is a method that has yet to be defined; it is simply a method signature. Any class that contains an abstract method must be an abstract class as we will later see.


A Visual Lab...

In order to make this lab more interesting, we will be using a Java library called Processing.


There is no need to be concerned with how the Processing library works. Our focus is on the what and how of Polymorphism. You will find all the information you need about the Shape, Rectangle and the Circle classes in the following slides.