辛格尔顿+抽象类问题
问题描述:
我试图定义这个继承:辛格尔顿+抽象类问题
public abstract class GameAction extends Observable {
protected static GameAction instance = null;
protected GameAction() {
// Exists only to defeat instantiation.
}
//All GameActions are singletons
public static abstract GameAction getInstance();
}
public class ChooseAnswerAction extends GameAction {
protected ChooseAnswerAction() {
// Exists only to defeat instantiation.
}
//All GameActions are singletons
@Override
public static GameAction getInstance() {
if(instance == null) {
instance = new ChooseAnswerAction();
}
return instance;
}
}
的问题是,在第二类中的方法getInstance()
没有找到他的父亲同一个,为此它要求我删除@Override
。
同样在父类中,我得到了以下错误:
The abstract method getInstance in type GameAction can only set a visibility modifier, one of public or protected
我能解决这个错误的唯一方法是取出static修饰符,但我需要它...
感谢对你的时间!
答
这是我去链接单身人士。由于AlekseyShipilёv做了一个非常详细的帖子 - 我在那里链接你。
http://shipilev.net/blog/2014/safe-public-construction/
在你的情况,因为你正在返回的孩子单个实例,我将建议实例对象是在子类。此外,您可能需要更好的设计,并考虑使用单件工厂。
答
简短的回答是,你不能覆盖静态方法,因为它们绑定到超类。
长的答案是,这使得实现单例继承变得复杂(假设你想在超类中保存实例)。请参阅singleton and inheritance in Java
静态方法和字段不是继承的,它们属于它们已定义的类,这就是为什么您无法覆盖它。出于同样的原因,静态方法不能是抽象的。 – m0skit0 2015-02-06 18:10:44