开发者

Force inherited classes to define method

开发者 https://www.devze.com 2023-01-25 18:34 出处:网络
The superclass is Account, and I have two subclasses - CurrentAccount and SavingsAccount. The superclass will have a method applyInterest(), which will calculate the interest using the rate specified

The superclass is Account, and I have two subclasses - CurrentAccount and SavingsAccount.

The superclass will have a method applyInterest(), which will calculate the interest using the rate specified by an inherited class. I don't know how to force a class to define this though.

The only option I can think of is to force the subclasses to implement applyInterest(), and just set the rate in ther开发者_Python百科e.


I'm not sure if I understand your question, but I think you may use the keyword abstract if you don't want to introduce an interface

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


You could force the subclasses to implement getInterestRate(), if that is preferable.


The best solution is to make the class Account as abstract. If you don't want to do this for any reason (then, Account must be instantiable) you can write:

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

Really, it's not the best idea in the world (the best idea is to make Account as abstract class), but when you test the subclass of Account and call the applyInterest(), this exception force you to implement this method in the subclass.

It's just another way.

0

精彩评论

暂无评论...
验证码 换一张
取 消