How static fields are referenced through objects? [duplicate]

只谈情不闲聊 提交于 2021-02-10 23:24:00

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!