【发布时间】:2010-11-17 11:36:36
【问题描述】:
超类是 Account,我有两个子类 - CurrentAccount 和 SavingsAccount。
超类将有一个方法 applyInterest(),它将使用继承类指定的利率计算利息。我不知道如何强制一个类来定义它。
我能想到的唯一选择是强制子类实现 applyInterest(),然后在其中设置费率。
【问题讨论】:
标签: java
超类是 Account,我有两个子类 - CurrentAccount 和 SavingsAccount。
超类将有一个方法 applyInterest(),它将使用继承类指定的利率计算利息。我不知道如何强制一个类来定义它。
我能想到的唯一选择是强制子类实现 applyInterest(),然后在其中设置费率。
【问题讨论】:
标签: java
我不确定我是否理解你的问题,但如果你不想介绍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);
}
}
【讨论】:
如果更可取,您可以强制子类实现 getInterestRate()。
【讨论】:
interestRate() 方法使超类抽象。这是一个比在两个子类中实现applyInterest() 更好的设计(子类没有定义如何应用利率的方式,正如我从问题中理解的那样)。
最好的解决方案是将类 Account 设为abstract。
如果您出于任何原因不想这样做(那么,Account 必须是可实例化的),您可以编写:
applyInterest(){
throw new RuntimeException("Not yield implemented");//or another Exception: IllegalState, NoSuchMethodException, etc
}
真的,这不是世界上最好的主意(最好的主意是让 Account 成为抽象类),但是当您测试 Account 的子类并调用 applyInterest() 时,会出现此异常强制你在子类中实现这个方法。
这只是另一种方式。
【讨论】: