Luane Platter

November 14-20, 2004

 

This week presented the advantages of polymorphism, as well as how to implement hierarchical structures in order to achieve these advantages.  A subclass extends a super class.  The super class has fields and methods that apply to all of its sub classes.  Sub classes inherit all the fields of a super class.

 

They can also append more fields if necessary.  Sub classes also inherit all  methods of its super class.  However, if desired, a sub class can override the method of the super class, provided the overriding method takes the same  parameters. 

 

For example, let me model a place of employment.  The super class is Employee, and the sub classes are Janitor and Secretary.  There is also a user interface class called Company, which is a grouping of Employees.  Some similar fields are String name, and int wage.  These fields go in the super class Employee.  Differing fields are Boolean worksNightShift for janitor, and String officeLocation for secretary. 

 

An example of overriding a method is to create a doJob method for the Employee class, which prints the line “Job is done”.  If this is overridden in the Janitor and Secretary classes, they could have different methods called, such as sweepFloors, and takeNotes.  If doJob is called on a Janitor object, “Floors have been swept” will be printed, and if called on a Secretary object “Notes have been taken” will be printed. 

 Let’s now say that the Company class has a field of type ArrayList, which stores a group of Employees, and a method called doAllJobs.  This method iterates through each of the Employee objects in the list, and has each one do their job.  Without polymorphism, a conditional statement would have to be written for each object type to assert which job should be done according to the object type.  With polymorphism, the doJob method of each sub class will be called automatically, so the Janitor will sweep the floors, and the Secretary will take notes.