Polymorphism

Problem

A collection needs to process its members. But different types of members may need to be processed in different ways.

Also, we want to allow new types of members to be added to the collection without making changes to the collection implementation.

Solution

Introduce a Member base class with an abstract processing method.

Introduce subclasses of this class corresponding to the different types of allowable members.

Each subclass should override the inherited processing method with a type-specific algorithm.

The collection class should contain no references to the Member subclasses.

Here's the design:

Implementation

See:

Collection.java

Applications

The CyberAir Flight Simulator

Ultimate Warrior

ABC

Variations

Member can be an interface instead of an abstract class. Choose abstract class if Member has other methods or fields worth inheriting.

Member can also provide a concrete implementation of the processing method if it is an acceptable default.

References

Basics

Advanced