CS3340:   Intro OOP and Design

 

Polymorphism

Polymorphism is a concept made possible by inheritance in which a name denotes instances of many different classes, as long as they are related by a common super-class.

 

Example:

public void paint() {

        Iterator it = shapes.iterator();

        while (it.hasNext()) {
          // polymorphism: shape can refer to squares,           //circles, triangles, etc.
        Shape shape = (Shape)shapes.next();

        shape.draw(); }

}

 

Example: Polymorphism solving design problem (encapsulation violation)

BAD: (a) Bad use of Constraint - an Account can have either Person OR Corporation associated with it. Violates encapsulation

GOOD: (b) Use polymorphism via inheritance to represent the disjunction.

 

© Lynne Grewe