如何强制在java中覆盖一个方法?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4203965/
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
How to force a method to be overridden in java?
提问by Hari Menon
I have to create a lot of very similar classes which have just one method different between them. So I figured creating abstract class would be a good way to achieve this. But the method I want to override (say, method foo()) has no default behavior. I don't want to keep any default implementation, forcing all extending classes to implement this method. How do I do this?
我必须创建许多非常相似的类,它们之间只有一种不同的方法。所以我认为创建抽象类将是实现这一目标的好方法。但是我想覆盖的方法(比如方法 foo())没有默认行为。我不想保留任何默认实现,强制所有扩展类实现此方法。我该怎么做呢?
采纳答案by Pablo Santa Cruz
You need an abstractmethod on your base class:
您的基类需要一个抽象方法:
public abstract class BaseClass {
public abstract void foo();
}
This way, you don't specify a default behavior andyou force non-abstract classes inheriting from BaseClass
to specify an implementation for foo
.
这样,您无需指定默认行为,而是强制继承自的非抽象类BaseClass
为foo
.
回答by Sean Patrick Floyd
Just make the method abstract.
只需将方法抽象化即可。
This will force all subclasses to implement it, even if it is implemented in a super class of the abstract class.
这将强制所有子类实现它,即使它是在抽象类的超类中实现的。
public abstract void foo();
回答by vitaut
Make this method abstract
.
使这个方法abstract
。
回答by Buhake Sindi
If you have an abstract class, then make your method (let's say foo
abstract as well)
如果您有一个抽象类,那么请创建您的方法(也可以说是抽象类foo
)
public abstract void foo();
Then all subclasses will have to override foo
.
然后所有子类都必须覆盖foo
.
回答by Jens Hoffmann
Just define foo() as an abstract method in the base class:
只需将 foo() 定义为基类中的抽象方法:
public abstract class Bar {
abstract void foo();
}
See The Java? Tutorials (Interfaces and Inheritance)for more information.
看到Java?教程(接口和继承)了解更多信息。