强制继承的类定义某些方法
我确信我记得读过有一种方法可以使超类的任何子类定义某些方法。我该怎么做?
在我的示例中,超类是 Account(并且是抽象的),子类是 SavingsAccount 和 CurrentAccount。所有子类必须实现自己的withdraw()方法。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
如果您将 Account 类和方法声明为抽象,那么如果您没有在扩展 Account 类的子类中实现抽象方法,编译器将会给您一个错误。
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.
如果 SavingAccount 和 CurrentAccount 彼此不了解并且各自扩展了 Account,那么您只需在 Account 类中简单地提及这一点:
因此派生类(如果它们不是抽象的)应该实现此方法。
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:
So the derived classes( if they are not abstract) should implement this method.
如果
Account 类
已经是抽象
。您可以添加一个名为withdraw()
的abstract
方法,例如:public abstract voidwithdraw();
这将强制 CurrentAccount 和 SavingsAccount 覆盖withdraw ()。
抽象类的好处是允许您添加子类(CurrentAccount、SavingsAccount)可以调用的方法(到 Account)。
这对于避免重复编写相同的代码非常有帮助。
此场景与您的案例中的工厂模式配合良好。
If the
Account class
is alreadyabstract
. You can add aabstract
method calledwithdraw()
, 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.
将
public Abstract voidwithdraw();
放入帐户中。Put
public abstract void withdraw();
in Account.在抽象类中定义该方法。
然后,任何扩展抽象类的类都将被迫实现
withdraw
方法。Define this method in the abstract class.
Then, any class that extends your abstract class will be forced to implement the
withdraw
method.