Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How static fields are referenced through objects? [duplicate]

Tags:

java

oop

static

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?

like image 362
swch Avatar asked Oct 21 '25 15:10

swch


1 Answers

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

like image 183
ernest_k Avatar answered Oct 23 '25 04:10

ernest_k



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!