好的,我正在从名为 MonthlyReports 的类中的有关客户的文件中读取大量信息。我还有一个名为 Customer 的类,并且想要重写其中名为 getTotalFees 的方法,并且我有两个名为 StandardCustomer 和 PreferredCustomer 的子类,我希望在其中重写 getTotalFees。读入的重要信息之一是客户是首选还是标准(存储在变量标志中,但是我的问题是我不知道应该在哪里/如何让它决定客户是否是标准或首选。
这是我的想法,在 Customer 类中我有抽象方法 getTotalFees
public double abstract getTotalFees() {
return this.totalFees;
}
然后在我的标准类和首选类中,我有覆盖它的方法
public double getTotalFees() {
if (flag.equals("S"){
return this.totalFees * 5;
} else {
return this.totalFees;
}
}
我真的只是在这里捕获救命稻草,所以任何帮助将不胜感激。
最佳答案
如果您已经有两个不同的类 StandardCustomer
和 PreferredCustomer
,您可以拥有该方法的两个不同版本:
//in StandardCustomer:
@Override
public double getTotalFees() {
return this.totalFees * 5;
}
//in PreferredCustomer:
@Override
public double getTotalFees() {
return this.totalFees;
}
Java 中的动态调度会根据实例的运行时类型来处理适当的方法。
关于java - java中的条件重写方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12631937/