SE450: Java: Types of Storage [21/22] ![]() ![]() ![]() |
What are class fields, object fields and method variables?
In java, a class field is also called static
field.
Object fields are also called instance fields.
When one discusses a field
, one is usually referring
to an instance field.
Class fields are stored once for the class. Lifetime is life of the class in memory. All instances (if any) share the same data.
Class fields are stored statically. For our purposes they are immortal.
Instance fields are stored once for the object. Lifetime is life of the object. All instances have separate data.
Instance fields are stored in an object record on the
heap. Heap allocation is indicated by the use of
new
, which returns a reference to the heap.
Java objects are garbage collected: an object dies
when the last reference to that object dies. (The memory
is reclaimed when the garbage collection thread removes the
object that the reference referred to).
Class fields and methods are referred to in java by ClassName.classMethod(Parameters) or ClassName.classField, or by an object reference: objectReference.classMethod(Parameters) or objectReference.classField. Instance fields and methods have to be referred to by objectReference.instanceMethod(Parameters) or objectReference.instanceField. You should use the ClassName, not an objectRefrence to access class fields and methods.
Class fields can be initialized with default values, in an initializer in its declaration, or in a static initialization block (like a class initialization block, but it is run once for all classes). Do not use the constructor.
Method variables (local variables and parameters) are stored once for each method invocation. Lifetime is life of the method invocation.
Method variables are stored in an activation record (or frame) on the stack.
In practice, the stack runs out of space when the OS runs out
of space. The heap runs out of space when the heap size is
reached. You can control this with -Xms
and
-Xmx
options on the java command line.