I have a Java class called Game which has a non-static integer called score.
I would like to implement a static method which would increase the score of each Game object by 1, named increaseAllScore(). Is this possible? Could I simulate something like this or is there any way around this?
You could do it with an implementation like this:
int score;
static int scoremodifier;
public static void increaseAllScore() {
scoremodifier++;
}
public int getScore() {
return score + Game.scoremodifier;
}
The only way to do this is to provide a mechanism for the static method to access a reference to the Game object(s). One way to do this is to have each Game object register itself in a static data structure.
For instance, you might do this:
public class Game {
private static Set<WeakReference<Game>> registeredGames
= new HashSet<WeakReference<Game>>();
private int score;
public Game() {
// construct the game
registeredGames.add(new WeakReference(this));
}
. . .
public static incrementAllScores() {
for (WeakReference<Game> gameRef : registeredGames) {
Game game = gameRef.get();
if (game != null) {
game.score++;
}
}
}
}
I'm using a WeakReference<Game>
here so that the set doesn't prevent the game from being garbage-collected when there are no other references to it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With