强制继承的类定义某些方法

发布于 2024-10-03 04:28:19 字数 139 浏览 6 评论 0原文

我确信我记得读过有一种方法可以使超类的任何子类定义某些方法。我该怎么做?

在我的示例中,超类是 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

碍人泪离人颜 2024-10-10 04:28:26

如果您将 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.

万劫不复 2024-10-10 04:28:25

如果 SavingAccount 和 CurrentAccount 彼此不了解并且各自扩展了 Account,那么您只需在 Account 类中简单地提及这一点:

public abstract <return type> withdraw();

因此派生类(如果它们不是抽象的)应该实现此方法。

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.

暖心男生 2024-10-10 04:28:24

如果Account 类 已经是抽象。您可以添加一个名为 withdraw()abstract 方法,例如:

public abstract voidwithdraw();

这将强制 CurrentAccount 和 SavingsAccount 覆盖withdraw ()。

抽象类的好处是允许您添加子类(CurrentAccount、SavingsAccount)可以调用的方法(到 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.

无声无音无过去 2024-10-10 04:28:23

public Abstract voidwithdraw(); 放入帐户中。

Put public abstract void withdraw(); in Account.

回梦 2024-10-10 04:28:22

在抽象类中定义该方法。

public abstract <returnType> withdraw();

然后,任何扩展抽象类的类都将被迫实现 withdraw 方法。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文