简体   繁体   中英

Accessing static variable from an object in memory

Recently, I learned that the static variable could be accessed from an object, in addition to a class name.

I believe that static variables reside in the permanent generation area in the heap, not in the object related area in the heap.

Also, I think that m1.count refers the memory position of m1, and add some offset to access the count instance variable.

In my logic, m1.count should spit error since there is no instance variable called count near m1 object in memory.

How could it be possible? I want to know how it works in memory. Here is the code:

class Member{
    public static int count;
}

public static void main(){    
    Member m1 = new Member();
    System.out.println(m1.count); // ???
}

I believe that static variables reside in the permanent generation area in the heap,

such static fields can be anywhere on the heap.

I think that m1.count refers the memory position of m1,

static fields ignore the reference. The reference can be null and the code will run fine.

I want to know how it works in memory

There is a special object for the static fields of the class. You can get this the with a heap dump. The reference is incidental.

This

Member m1 = new Member();
System.out.println(m1.count); 

is the same as

Member m1 = null;
System.out.println(m1.count); 

which is the same as

System.out.println(Member.count); 

I believe that static variables reside in the permanent generation area in the heap, not in the object related area in the heap.

Well to put it more simply they reside in the class, not in the object.

Also, I think that m1.count refers the memory position of m1, and add some offset to access the count instance variable.

No. It essentially does m1.class.count, but the m1.class part happens at compile time.

In my logic, m1.count should spit error since there is no instance variable called count near m1 object in memory.

Ergo your logic is wrong.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM