【问题标题】:Conditionally overriding methods in java有条件地覆盖java中的方法
【发布时间】:2012-09-19 20:41:27
【问题描述】:

好的,我正在从名为 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;
    }
}

我真的只是在这里抓住稻草,所以任何帮助都将不胜感激。

【问题讨论】:

    标签: java conditional overriding


    【解决方案1】:

    听起来你需要一个工厂方法(又名“虚拟构造函数”)。让多态为你解决这个问题。这是面向对象编程的标志之一:

    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();
            }
        }
    }
    

    【讨论】:

      【解决方案2】:

      如果您已经有两个不同的类StandardCustomerPreferredCustomer,您可以有两个不同版本的方法:

      //in StandardCustomer: 
      @Override
      public double getTotalFees() {
           return this.totalFees * 5;
      }
      
      //in PreferredCustomer: 
      @Override
      public double getTotalFees() {
           return this.totalFees;
      }
      

      Java 中的动态分派负责根据实例的运行时类型涉及正确的方法。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-01-01
        • 2021-09-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多