1

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); // ???
}
1
  • 1
    you are not the only one. many people believe this "feature" is a mistake in the language design. Commented Feb 11, 2016 at 2:01

2 Answers 2

3

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); 
Sign up to request clarification or add additional context in comments.

Comments

1

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.

2 Comments

Lawrey suggested that m1 could be null. Then, what is the output of null.class?
@PeterHwang null.class is not the correct construct. Member.class will still be the Class<Member>, while d.class will NPE.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.