问题描述
我必须创建许多非常相似的类,它们之间只有一种方法不同.因此,我认为创建抽象类将是实现此目标的好方法.但是我要覆盖的方法(例如,方法foo())没有默认行为.我不想保留任何默认实现,而是强制所有扩展类都实现此方法.我该怎么做?
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?
推荐答案
您需要在基类上使用抽象方法:
You need an abstract method on your base class:
public abstract class BaseClass {
public abstract void foo();
}
这样,您无需指定默认行为,并且您将强制从 BaseClass
继承的非抽象类指定 foo
.
This way, you don't specify a default behavior and you force non-abstract classes inheriting from BaseClass
to specify an implementation for foo
.
这篇关于如何强制在Java中重写方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!