问题
Suppose I have this simple class:
public class Car {
public static final int TYPE_SUV = 1;
public static final int TYPE_TRUCK = 2;
public String name;
public int carType;
}
Now if I have a collection of these, I know that I am allocating a String and an int for each element in the collection, but am I also storing static ints multiple times? This contrived example class is representative of the kind of Java I wrote years ago before I learned that magic numbers like this are better served with an enum which is defined in a separate class, but I've always wondered what the side effect of this code is.
回答1:
From the 1.7 JLS:
If a field is declared static, there exists exactly one incarnation of the field, no matter how many instances (possibly zero) of the class may eventually be created. A static field, sometimes called a class variable, is incarnated when the class is initialized (§12.4).
A field that is not declared static (sometimes called a non-static field) is called an instance variable. Whenever a new instance of a class is created (§12.5), a new variable associated with that instance is created for every instance variable declared in that class or any of its superclasses.
The key point to note is that memory is consumed on a per-class (not instance) basis, irrespective of how many instances you have (1, 1000 or none).
For what it's worth:
Your name and carType instance variables are only allocated when an instance is created. What's more, before java 7, Strings of an equal value could be interned - maintained in a single String instance that is referenced wherever used - into a String-managed memory (in PermGen). This changed with java 1.7 when it was moved to the main heap and seems to be changing again(?) with java 8
回答2:
No copies are stored anywhere, multiple references to the same location in memory (on the heap ) are created.
回答3:
static variable are related to class not with Object. So as many Object you create but static variable will be once get spaced in memory and all the Static context loads at class loading time so without creating Object also you can access your static variable with the help of class name.
回答4:
No multiple copies of static is maintained. all objects have same static variables. If they have it then you have to access them using object but this is not what we do with static.
The Penalty of storing references = penalty of creating the class.
来源:https://stackoverflow.com/questions/14984581/how-many-copies-of-a-static-final-property-are-stored-in-memory-when-i-have-a-co