【问题标题】:Force inherited classes to define method强制继承的类定义方法
【发布时间】:2010-11-17 11:36:36
【问题描述】:

超类是 Account,我有两个子类 - CurrentAccount 和 SavingsAccount。

超类将有一个方法 applyInterest(),它将使用继承类指定的利率计算利息。我不知道如何强制一个类来定义它。

我能想到的唯一选择是强制子类实现 applyInterest(),然后在其中设置费率。

【问题讨论】:

    标签: java


    【解决方案1】:

    我不确定我是否理解你的问题,但如果你不想介绍interface,我想你可以使用关键字abstract

    public abstract class Account
    {
        public int applyInterest()
        {
            return 10 * getInterestRate();
        }
        abstract protected int getInterestRate();
    }
    

    public class CurrentAccount extends Account
    {
        protected int getInterestRate() { return 2; }
    }
    

    public class SavingsAccount extends Account
    {
        protected int getInterestRate() { return 3; }
    }
    

    import static org.junit.Assert.assertTrue;
    import org.junit.Test;
    public class AccountTest
    {
       @Test
       public void currentAccount()
       {
           Account ca = new CurrentAccount();
           assertTrue(ca.applyInterest()==20);
       }
       @Test
       public void savingsAccount()
       {   
           Account sa = new SavingsAccount();
           assertTrue(sa.applyInterest()==30);
       }
    }
    

    【讨论】:

      【解决方案2】:

      如果更可取,您可以强制子类实现 getInterestRate()。

      【讨论】:

      • 确实如此。使用抽象interestRate() 方法使超类抽象。这是一个比在两个子类中实现applyInterest() 更好的设计(子类没有定义如何应用利率的方式,正如我从问题中理解的那样)。
      • 所以每种类型的账户都必须实现它自己的 interestRate() 方法,其中将包含一行设置利率?甚至可能不会调用 interestRate() 方法,因此利率可能会保持为零。
      • 建议超类在 applyInterest() 中从相关子类调用 getInterestRate()。这允许每个子类指定其利率,但将逻辑保留在一个位置 (applyInterest) 以防您需要更改它(例如,更改舍入行为)。
      【解决方案3】:

      最好的解决方案是将类 Account 设为abstract。 如果您出于任何原因不想这样做(那么,Account 必须是可实例化的),您可以编写:

      applyInterest(){
      throw new RuntimeException("Not yield implemented");//or another Exception: IllegalState, NoSuchMethodException, etc
      }
      

      真的,这不是世界上最好的主意(最好的主意是让 Account 成为抽象类),但是当您测试 Account 的子类并调用 applyInterest() 时,会出现此异常强制你在子类中实现这个方法。

      这只是另一种方式。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-10-28
        • 1970-01-01
        • 2012-05-05
        • 2016-07-06
        • 2013-11-09
        • 1970-01-01
        • 2012-04-21
        相关资源
        最近更新 更多