Tuesday, January 31, 2017

Polymorphism, Abstract Classes and Interfaces

This week, the focus of our studies are polymorphism -- another pillar, if you will, along with inheritance and encapsulation, of object-oriented programming -- abstract classes and interfaces.

Inheritance allows for the defining of general classes, called superclasses, which can then be extended to a variety of specialized, instance-of subclasses.  Basically, the concept of polymorphism is when any one of those subtypes, belonging to the latter, subclass, can be passed into the superclass' methods or work with the superclass' variables.  Since the subtype is an instance of the supertype, (and not vice-versa), its many forms, created through subclasses, can each be used with it.  It's probably easiest to describe with an example, such as a geometric object superclass that has subtypes of circles or squares.  These might each have instances that could be passed into the superclass GeometricObject's methods, for example, maybe a color setter.  Or, their member properties could refer to the superclass' data definitions, such as one for color.  I think polymorphism can also refer to method overriding, where you have similar method definitions in each of the subtypes, but different executions in each version.

The abstract class cannot have any concrete  types, no instantiations, so it would never be called or implemented with the new object operator.  The purpose of the abstract class is to define these common features, and allow reuse and convenient interaction.  For example, a circle and square's overriden getArea method allows for an additional method of comparison of this data that was achieved through different calculations.

While an abstract superclass defines common behavior and features for connected, related subclasses, the interface defines behavior for any class, whether or not it's related to it.  Java provides some interfaces such as Comparable and Clonable, which a variety of other classes, whether pre-defined in the Java library or homemade, can implement.

No comments:

Post a Comment