问题
I understand what static is but I can't find information how are the static fields referenced through the objects.
Let's imagine that we have two classes:
class Foo {
static int statValue = 10;
}
class Bar {
public static void main(String[] args) {
Foo foo1 = new Foo();
int valFromObject = foo1.statValue;
int valFromClass = Foo.statValue;
}
}
When we run this program we have one object on heap (foo1), and two classes in metaspace (simplified).
When we access static field through the class:
int valFromClass = Foo.statValue;
it is easy, because I assume that we reference class object in metaspace. But how are the static members accessed through the objects? When we write:
int valFromObject = foo1.statValue;
is the Foo instance actually involved or it is bypassed and
foo1.statValue;
Foo.statValue
are synonyms?
回答1:
The instance is in fact not used. Java uses the type of the variable, and then reads the static (class) field.
That's why even a null with the correct type won't raise a null pointer exception.
Try this:
Foo foo1 = null;
int valFromObject = foo1.statValue; //will work
Or this:
int valFromNull = ((Foo)null).statValue; //same thing
Accessing static class members through instances is discouraged for obvious reasons (the most important being the illusion that an instance member is being referenced, in my opinion). Java lets use foo1.statValue
, with a warning ("The static field Foo.statValue should be accessed in a static way"
as reported by my IDE).
来源:https://stackoverflow.com/questions/53483241/how-static-fields-are-referenced-through-objects