0

I have a package with different classes. One class implements a structure data. I want to use an instance of this class as a global variable in all the classes of my package. How can I use and modify this variable, remaining its content.

Creating a static variable is not what I need, because I need to modify it, not just read it.

Fernando Á.
  • 7,295
  • 7
  • 30
  • 32
  • 1
    static variables can be modified... (not that they're a good idea to use in this way, though) – Jason S Mar 13 '12 at 18:06
  • 2
    As people said, you can modify a static variable. But you must seriously think about changing your design. Global state is very rarely justified. – Savvas Dalkitsis Mar 13 '12 at 18:08
  • possible duplicate of [Global variables in Java](http://stackoverflow.com/questions/4646577/global-variables-in-java) – Paolo Falabella Mar 13 '12 at 18:09

5 Answers5

1

You can always modify the content of static variable(its final which you can't modify),

It would be nice if you wrap up all the data into a singleton instance and share that instance

jmj
  • 237,923
  • 42
  • 401
  • 438
1

something like this?

class MyMetadata
{
    private int x;
    private int y;
    public int getX() { return this.x; }
    public int getY() { return this.y; }
    public void setX(int newX) { this.x = x; }
    public void setY(int newY) { this.y = y; }
    MyMetadata(int x, int y) { this.x = x; this.y = y; }

    static final private MyMetadata INSTANCE = new MyMetadata(0,0);
    static public MyMetadata getInstance() { return INSTANCE; }
}

// in client code:
int needsX = MyMetadata.getInstance().getX();

Just be sure to handle concurrency issues carefully.

Jason S
  • 184,598
  • 164
  • 608
  • 970
0

There is nothing that says a static variable can't be reassigned to. "static" in this case just means it is not associated with an instance.

On the other hand, the final modifier prevents a variable from being re-assigned to.

That being said, I would highly encourage trying to avoid the use of a [writeable] static variable. Generally I find this can be encapsulated as some sort of state instance: singleton (ick!) or otherwise.

Happy coding.

0

Remove the 'final' keyword from the static and then you can modify it.

static int globalInt = -42;

Can be used and/or updated anywhere.

Java42
  • 7,628
  • 1
  • 32
  • 50
0

The only way to share instance across application is by Singleton mechanism. But its becoming an anti pattern recently as it makes hard to maintain and also test such applications. There are lots of explanation on that why its an anti pattern on the web.

As told by others static variables can be modified, finals are the ones which cannot be.

raddykrish
  • 1,866
  • 13
  • 15