简体   繁体   English

如何强制在java中重写方法?

[英]How to force a method to be overridden in java?

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. 但是我想要覆盖的方法(例如,方法foo())没有默认行为。 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();
}

This way, you don't specify a default behavior and you force non-abstract classes inheriting from BaseClass to specify an implementation for foo . 这样,您不指定默认行为, 强制从BaseClass继承的非抽象类指定foo的实现。

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™教程(接口和继承)

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();

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

使这个方法abstract

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM