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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7381006/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 19:44:12  来源:igfitidea点击:

Java: Force subclasses to override methods of the Superclass

javamethodsoverridingsuperclass

提问by Dj Boris

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".

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

Thanks

谢谢

回答by aioobe

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

如何编写方法并强制子类覆盖此方法。

Declare the method as abstract:

将方法声明为abstract

enter image description here

在此处输入图片说明

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

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

回答by Chris Eberle

Just declare the method as abstractin the base class. All children classes will then be forced to implement it. Alternatively you could also use an interfaceinstead 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.

只需在基类中将该方法声明为抽象方法即可。然后将强制所有子类实施它。或者,您也可以使用接口而不是具体类,这只是约定将实现定义的方法。任何一种都可以,这取决于您的需求。

回答by rsp

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

您可以通过制作方法abstract(不提供默认实现)来做到这一点。

回答by Oliver Charlesworth

Declare the method as abstract.

将方法声明为abstract.

回答by Lemuel Adane

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.

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