Visiting Several Classes The Visitor becomes more useful,
Visiting Several Classes The Visitor becomes more useful, when there are a number of different classes with different interfaces and we want to encapsulate how we get data from these classes. Let s extend our vacation days model by introducing a new Employee type called Boss. Let s further suppose that at this company, Bosses are rewarded with bonus vacation days (instead of money). So the Boss class as a couple of extra methods to set and obtain the bonus vacation day information: public class Boss extends Employee { private int bonusDays; public Boss(String name, float salary, int vacdays, int sickdays) { super(name, salary, vacdays, sickdays); } public void setBonusDays(int bonus) { bonusDays = bonus; } public int getBonusDays() { return bonusDays; } public void accept(Visitor v) { v.visit(this); } } When we add a class to our program, we have to add it to our Visitor as well, so that the abstract template for the Visitor is now: public abstract class Visitor { public abstract void visit(Employee emp); public abstract void visit(Boss emp); } This says that any concrete Visitor classes we write must provide polymorphic visit methods for both the Employee and the Boss class. In the case of our vacation day counter, we need to ask the Bosses for both regular and bonus days taken, so the visits are now different. We ll write a new bVacationVisitor class that takes account of this difference: public class bVacationVisitor extends Visitor { int total_days; public bVacationVisitor() { total_days = 0; } public int getTotalDays() { return total_days; } //——————————- public void visit(Boss boss) { total_days += boss.getVacDays(); total_days += boss.getBonusDays(); } //—————————-public void visit(Employee emp) {
Note: If you are looking for good and high quality web space to host and run your application check Lunarwebhost Java Web Hosting services