Wednesday 7 May 2014

Basic Polymorphism in java

The word "polymorphism" means "many forms". It comes from Greek word "poly" (means many) and "morphos" (means form). For examples, in chemistry, carbon exhibits polymorphism because it can be found in more than one form: graphite and diamond. Each of the form has it own distinct properties.
A subclass possesses all the attributes and operations of its superclass (because a subclass inherited all attributes and operations from its superclass). This means that a subclass object can do whatever its superclass can do. As a result, we can substitute a subclass instance when a superclass instance is expected, and everything shall work fine. This is called substitutability.
In our earlier example of Circle and Cylinder: Cylinder is a subclass of Circle. We can say that Cylinder "is-a" Circle (actually, it "is-more-than-a" Circle). Subclass-superclass exhibits a so called "is-a" relationship.
Via substitutability, we can create an instance of Cylinder, and assign it to a Circle (its superclass) reference, as follows:

// Substitute a subclass instance to its superclass reference
Circle c1 = new Cylinder(5.0);
You can invoke all the methods defined in the Circle class for the reference c1, (which is actually holding a Cylinder object), e.g. c1.getRadius() and c1.getColor(). This is because a subclass instance possesses all the properties of its superclass.
However, you cannot invoke methods defined in the Cylinder class for the reference c1, e.g. c1.getHeight() and c1.getVolume(). This is because c1 is a reference to the Circle class, which does not know about methods defined in the subclass Cylinder.
c1 is a reference to the Circle class, but holds an object of its subclass Cylinder. The reference c1, however, retains its internal identity. In our example, the subclass Cylinder overrides methods getArea() and toString(). c1.getArea() or c1.toString() invokes the overridden version defined in the subclass Cylinder, instead of the version defined in Circle. This is because c1 is in fact holding a Cylinder object internally.

Summary
  1. A subclass instance can be assigned (substituted) to a superclass' reference.
  2. Once substituted, we can invoke methods defined in the superclass; we cannot invoke methods defined in the subclass.
  3. However, if the subclass overrides inherited methods from the superclass, the subclass (overridden) versions will be invoked.

0 comments:

Post a Comment