4

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).

enter image description here

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?

2
  • The static type of foo1 (the type that was used to declare the variable, in this case Foo) is used to access the static field. The actual instance does not play a role. Commented Nov 26, 2018 at 14:30
  • Note that foo1.statValue will yield a compiler warning. You shouldn't even be writing code like that. Commented Nov 26, 2018 at 14:34

1 Answer 1

9

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).

Sign up to request clarification or add additional context in comments.

1 Comment

I'm still wondering why they allowed foo1.statValue; in the first place.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.