Although we cannot instantiate objects of abstract superclasses, you’ll soon see that we can use abstract superclasses to declare variables that can hold references to objects of any concrete class derived from those abstract superclasses. Programs typically use such variables to manipulate subclass objects polymorphically. You also can use abstract superclass names to invoke static
methods declared in those abstract superclasses.
Consider another application of polymorphism. A drawing program needs to display many shapes, including types of new shapes that you’ll add to the system after writing the drawing program. The drawing program might need to display shapes, such as Circle
s, Triangle
s, Rectangle
s or others, that derive from abstract class Shape
. The drawing program uses Shape
variables to manage the objects that are displayed. To draw any object in this inheritance hierarchy, the drawing program uses a superclass Shape
variable containing a reference to the subclass object to invoke the object’s draw
method. This method is declared abstract
in superclass Shape
, so each concrete subclass must implement method draw
in a manner specific to that shape—each object in the Shape
inheritance hierarchy knows how to draw itself. The drawing program does not have to worry about the type of each object or whether the program has ever encountered objects of that type.