Java:强制子类覆盖超类的方法

发布于 2024-12-04 10:15:05 字数 77 浏览 3 评论 0原文

如何编写一个方法并强制子类重写该方法。在 Eclipse 中,它应该显示在“快速修复”对话框中:“添加未实现的方法”。

谢谢

How can I write a method and force the subclasses to override this method. In Eclipse it should show in the Quick-Fix Dialog: "Add unimplemented methods".

Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(5

绅刃 2024-12-11 10:15:05

如何编写一个方法并强制子类重写该方法。

将该方法声明为abstract

在此处输入图像描述

Eclipse 将为您提供所有(未实现的)抽象方法和接口方法的“添加未实现的方法”选项。

How can I write a method and force the subclasses to override this method.

Declare the method as abstract:

enter image description here

Eclipse will give you the "Add unimplemented methods"-option for all (unimplemented) abstract methods and interface methods.

情定在深秋 2024-12-11 10:15:05

只需在基类中将该方法声明为 abstract 即可。所有儿童班级将被迫执行。或者,您也可以使用 接口 而不是具体类,这只是一个协议将实施定义的方法。两者都可以,这取决于您的需求。

Just declare the method as abstract in the base class. All children classes will then be forced to implement it. Alternatively you could also use an interface instead of a concrete class, which is simply an agreement that the methods defined will be implemented. Either one is fine, it depends on your needs.

佼人 2024-12-11 10:15:05

您可以通过使方法抽象(不提供默认实现)来做到这一点。

You can do that by making the method abstract (not providing a default implementation).

蓦然回首 2024-12-11 10:15:05

或者,如果您不希望您的类成为抽象类,您可以在您想要强制覆盖的方法处抛出您自己的 MustOverrideException。

Or if you do NOT want your class to be an abstract class, you can throw your own MustOverrideException at the method that you want to force to be overridden.

冷心人i 2024-12-11 10:15:05

将方法声明为抽象

Declare the method as abstract.

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