Reputation: 1478
I'm trying to define this inheritance:
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;
}
}
The problem is that the getInstance()
method in the second class doesn't find the same one on his father, therefor it asks me to remove the @Override
.
Also on the parent class I get the following error:
The abstract method getInstance in type GameAction can only set a visibility modifier, one of public or protected
The only way I could fix this error was taking out the static modifier, but I need it...
Thank's for your time!
Upvotes: 0
Views: 4468
Reputation: 907
The short answer is, that you can't override static methods since they are bound to the superclass.
The long answer is, that this makes implementing singleton inheritances complicated (assuming you want to hold the instance in the superclass). See singleton and inheritance in Java
Upvotes: 0
Reputation: 580
Here is my go to link on singleton. Since Aleksey Shipilёv has made a very detailed post - I am linking you there.
http://shipilev.net/blog/2014/safe-public-construction/
In your case, since you are returning the child singleton instance, I would recommend that the instance object be in the child class. Also, you may want a better design and think about using a singleton factory.
Upvotes: 2