Reputation: 11347
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.
Upvotes: 2
Views: 579
Reputation: 43108
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.
Upvotes: 1
Reputation: 1828
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.
Upvotes: 0
Reputation: 5963
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.
Upvotes: 1
Reputation: 138922
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.
Upvotes: 7