Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How would I use a static method to increase a non-static variable?

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?

like image 960
claudio Avatar asked Feb 18 '23 12:02

claudio


2 Answers

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;
}
like image 107
femtoRgon Avatar answered Feb 21 '23 01:02

femtoRgon


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.

like image 24
Ted Hopp Avatar answered Feb 21 '23 01:02

Ted Hopp