Force inherited classes to define certain methods
I'm sure I remember reading that开发者_如何学运维 there is a way to make any subclass of the superclass define certain methods. How do I do it?
In my example, the superclass is Account (and is abstract), and the subclasses are SavingsAccount and CurrentAccount. All subclasses must implement their own withdraw() method.
Define this method in the abstract class.
public abstract <returnType> withdraw();
Then, any class that extends your abstract class will be forced to implement the withdraw
method.
Put public abstract void withdraw();
in Account.
If the Account class
is already abstract
. You can add a abstract
method called withdraw()
, example:
public abstract void withdraw();
This will force CurrentAccount and SavingsAccount to override withdraw().
The benefit you have of the abstract class is to allow you to add methods (to Account) that the subclasses (CurrentAccount,SavingsAccount) can call.
This is very helpful to avoid writing the same code twice.
This scenario works well with a factory pattern in your case.
if SavingAccount and CurrentAccount don't know about each other and each extends the Account, so you have to just simply mention this in your Account class:
public abstract <return type> withdraw();
So the derived classes( if they are not abstract) should implement this method.
If you declared you Account class and method as abstract, then compiler will give you an error if you don't implement abstract method in your subclasses that extend Account class.
精彩评论