Java:强制子类覆盖超类的方法
如何编写一个方法并强制子类重写该方法。在 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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
将该方法声明为
abstract
:Eclipse 将为您提供所有(未实现的)抽象方法和接口方法的“添加未实现的方法”选项。
Declare the method as
abstract
:Eclipse will give you the "Add unimplemented methods"-option for all (unimplemented) abstract methods and interface methods.
只需在基类中将该方法声明为 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.
您可以通过使方法
抽象
(不提供默认实现)来做到这一点。You can do that by making the method
abstract
(not providing a default implementation).或者,如果您不希望您的类成为抽象类,您可以在您想要强制覆盖的方法处抛出您自己的 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.
将方法声明为
抽象
。Declare the method as
abstract
.