Re: Static Versus Non Static
Arne Vajh?j <arne@vajhoej.dk> writes:
But the second one is the one being discussed here.
Then it's even more strange: The classes are globally (within a
classloader) accessible identifiers. The two real differences between
instance and static in Java is that instance methods are virtual, and
that instance references - methods or fields alike - need an object
reference on the stack.
Then the question becomes why an instance should be able to read a
static field (which is very useful for constants) but not write to it
(which appears to be what the OP reacts to). Java does not have access
modifiers for that, but there are two solutions:
1) Place the "guarded" static content in a different class.
// Package needs to be sealed in the jar so the library user
// cannot add to it.
package my.special.component;
public class MyStaticContent {
// The guarded data
private static int someValue = 42;
// No instances
private MyStaticContent() { }
// Public read method
public static int getSomeValue() {
return someValue;
}
// Mutating method is only visible to package.
static void setSomeValue(int value) {
someValue = value;
}
}
The problem is that the user conceivably could add a class in that
package anyway and add it to the library jar. Unless it was signed, in
which case that would fail to work.
It all depends on how important it is to not be able to mutate it
outside of static methods.
A better approach is
2) Use only instances and no static data. Manage all objects in a
container - like Spring. For the data that used to be static, use a
factory that produces one singleton object that is assigned to all
the objects that need the data it contains.