Reputation: 103
Okay so I am reading in a bunch of information from a file about customers in a class called MonthlyReports. I also have a class called Customer and want to override a method within it called getTotalFees, and I have two subclasses classes called StandardCustomer and PreferredCustomer where I want getTotalFees to be overridden. One of the important pieces of information that is read in is whether the customer is preferred or standard (which is stored in the variable flag, however my problem is I don't know where/how I should have it decide whether the customer is standard or preferred.
Here was my idea, in the Customer class I have the abstract method getTotalFees
public double abstract getTotalFees() {
return this.totalFees;
}
then in my Standard and Preferred Classes I have the methods that override it
public double getTotalFees() {
if (flag.equals("S"){
return this.totalFees * 5;
} else {
return this.totalFees;
}
}
I am really just grasping at straws here so any help would be appreciated.
Upvotes: 2
Views: 3156
Reputation: 308968
Sounds like you need a factory method (aka "virtual constructor"). Let polymorphism solve this problem for you. This is one of the hallmarks of object-oriented programming:
public class StandardCustomer extends Customer {
// There's more - you fill in the blanks
public double getTotalFees() { return 5.0*this.totalFees; }
}
public class PreferredCustomer extends Customer {
// There's more - you fill in the blanks
public double getTotalFees() { return this.totalFees; }
}
public class CustomerFactory {
public Customer create(String type) {
if ("preferred".equals(type.toLowerCase()) {
return new PreferredCustomer();
} else {
return new StandardCustomer();
}
}
}
Upvotes: 1
Reputation: 262764
If you already have two different classes StandardCustomer
and PreferredCustomer
you can have two different versions of the method:
//in StandardCustomer:
@Override
public double getTotalFees() {
return this.totalFees * 5;
}
//in PreferredCustomer:
@Override
public double getTotalFees() {
return this.totalFees;
}
Dynamic dispatch in Java takes care that the proper method is involved depending on the runtime type of the instance.
Upvotes: 4