Computer Science Courses
Related sites
Lab 5 |
Exploring small class hierarchies and polymorphism
Building on the homework 4 exercise.
Extend (and modify as needed) your Student class from Lab 4 tocreate a ResearchStudent subclass. This class will need to have an additional field which is the name of the supervisor.Create a printInfo() method to print out the students' fields and,in the case of the research student, their supervisor.
Write StudentTest class.Create an ArrayList
of your Student and ResearchStudent classes. Add a mix of students and research students, then loop the ArrayList
calling your printInfo() method.
Using the getClass() method, loop through ArrayList
and print out whether the class is a Student or a ResearchStudent.
Repeat the exercise above, this time using the instanceof operator.
Change Student into an abstract class by removingimplementation of printInfo() method. Subclass it intoUndegraduate and ResearchStudent accordingly.Modify the StudentTest class to work with Studenttype as elements of ArrayList
. Make the code to print thelist of students from the ArrayList
without using thegetClass() or instanceof but relying onpolymorphism instead. Now the code is much simpler —think this over.
Imaging that your type hierarchy is large and deep — let's nottalk about students, but about employees in a gigantic organization;very many different types of employee, all have the same number ofoverridden methods, declared in the abstract class Employee:printInfo(), calculateSalary(), paySupaContribution(), calculatePaidLeave() etc.There are Clerks, Managers, GeneralStaff,SeniorManagers, CEOs, Cleaners and so on.They all have different employment conditions, and differentimplementation of the above methods. Imaging also that the number ofoperations (methods) which we would like all our types to be ableto perform is changeable, it can grow. To implement newly addedmethods in each and every subclass of Employee can quicklybecome quite a task.
There is a better way: to remove all methods from Employeeand its subclasses and replace them with just one:
public abstract void accept(Visitor visitor);
Here, Visitor is a new type represented by an interfaceand a hierarchy of classes which implement it. The Visitordeclares all the methods which were removed from the Employeehiearchy:
public void visit(Clerk c);public void visit(Manager m);public void visit(Cleaner c);public void visit(GeneralStaff gs);....
and the classes implementing Visitor, provide implementationbodies for all visit-methods:
class SalaryCalculator implements Visitor { private double salary; public void visit(Clerk c) { salary = c.getSalary(); } public void visit(Manager m) { salary = c.getSalary() + c.getBonus(); } ...... public double calculate() { return salary; }}
and similarly for all other Visitor classes. The Employeehierarchy classes all have the same implementation of the acceptmethod:
When a client have a number of Employee objects and wants tocall the same operation of them (to calculate total salary part of the budget,or print the organization roll, it would (while looping through theemployee list) simply call:public void accept(Visitor v) { v.visit(this);}
SalaryCalculator sc = new SalaryCalculator();employee.accept(sc);total += sc.calculate();
The "invited" visitor will come to the caller object (thisreference!) and do what was asked.
The visitor pattern is particularly effective what the visited(Employee here) hierarchy types are defined recursively(expression trees).
Confused? Intrigued? Learn more about the Visitor pattern(search the web), and try to use in the above "Student" (or "Employee")examples. If thrilled, do more research and find out why the Visitor Patternis such a double-edged sword — discover problems which its use may create that turn advantages into liabilities.
Lab 5 |
Updated: Sun 12 Jun 2016 17:27:37 AEST • Responsible Officer: JavaScript must be enabled to display this email address. • Page Contact:
+61 2 6125 5111
The Australian National University, Canberra
CRICOS Provider : 00120C ABN : 52 234 063 906