Sub topic 1
Class-level versus object-level members
Prerequisites
This chapter assumes you can already do the following:
- Define a class with fields, constructors, and methods.
- Create objects with
newand call instance methods on them. - Use the
publicandprivateaccess modifiers. - Read basic inheritance code, including method overriding.
You don't need any knowledge of static yet. This chapter builds the model that the rest of the tutorial uses.
Two kinds of members
A class can declare several kinds of members: fields, methods, nested classes, and initializer blocks. Each member belongs to one of two groups:
- An instance member belongs to an individual object. Every object created with
newgets its own copy of each instance field. An instance method runs on one particular object and can read that object's fields. - A class member belongs to the class itself. You mark it with the
statickeyword. There is one copy per class, however many objects exist, including zero.
A useful way to think about it: the class is a blueprint, and each object is a house built from it. The blueprint has the same address list, the same builder's phone number, and the same count of houses built so far. Each house has its own paint color. The paint color is instance state. The count of houses built is class state.
| Aspect | Instance member | Static (class) member |
|---|---|---|
| Declared with | No modifier | `static` |
| Copies in memory | One per object | One per class |
| Exists before any `new` | No | Yes, once the class is initialized |
| Reached through | An object reference | The class name (preferred) |
| Has `this` | Yes | No |
| Typical use | Per-object state and behavior | Shared state, constants, helpers |
Seeing the difference in code
The class below tracks how many objects have been created. The counter is shared. The id is not.
public class Counter {
private static int created = 0;
private final int id;
public Counter() {
created++;
id = created;
}
public int getId() {
return id;
}
public static int getCreated() {
return created;
}
public static void main(String[] args) {
Counter first = new Counter();
Counter second = new Counter();
System.out.println(first.getId());
System.out.println(second.getId());
System.out.println(Counter.getCreated());
}
}This prints 1, 2, and 2. Each Counter has its own id, set once in the constructor. The field created has a single storage location. Both constructor calls increment that same location.
Notice how the two methods differ:
getId()is an instance method. You call it on an object:first.getId().getCreated()is a static method. You call it on the class:Counter.getCreated(). No object is needed, so it works even before the firstnew Counter().
Where each member lives
The exact memory layout is a JVM implementation detail, but the observable model is simple:
- Instance fields are stored with each object. Creating 1,000 objects with an
intfield allocates 1,000 of those fields. - A static field is stored once, with the loaded class. It is created when the class is initialized and stays for as long as the class stays loaded.
- Methods are not copied per object. Instance and static methods both exist once. The difference is what they receive. An instance method gets a hidden reference to the object it was called on, which you see as
this. A static method gets no such reference.
Class loaders can multiply "one copy"
"One copy per class" really means one copy per class as loaded by a given class loader. Two loaders that each load the same class file produce two distinct classes, each with its own static fields. Most programs use a single loader for their own code, so you will rarely see this. Application servers and plugin systems do hit it. It is one reason static state can behave unexpectedly in those environments.
How you reach each kind of member
Instance members need an object. Static members are reached through the class name. Java also lets you write a static member through an object reference, which compiles but misleads readers.
public class AccessDemo {
static int shared = 10;
int own = 5;
public static void main(String[] args) {
AccessDemo a = new AccessDemo();
AccessDemo b = new AccessDemo();
a.own = 50;
a.shared = 99; // legal, but misleading
System.out.println(b.own);
System.out.println(b.shared);
System.out.println(AccessDemo.shared);
AccessDemo none = null;
System.out.println(none.shared);
}
}The output is 5, 99, 99, and 99:
- Changing
a.ownleavesb.ownat5, because each object has its own field. - Writing
a.shared = 99changes the one shared field, sob.sharedandAccessDemo.sharedboth show99. - Reading
none.sharedthrough anullreference does not throw aNullPointerException. The compiler resolves a static member from the declared type of the expression. It never follows the reference. For a static field, the expressionnoneis not even evaluated to find the field.
What counts as a class member
Static applies to more than fields and methods. The full list is:
- Static fields: shared state, covered in the next chapter.
- Static methods: behavior that needs no object, covered after that.
- Static initializer blocks: code that runs once when the class is initialized.
- Static nested classes: classes declared inside another class that do not hold a reference to an enclosing object.
A top-level class cannot itself be static. The modifier is only legal on members, so a top-level class is always its own top-level scope. The nested form appears later in this tutorial.
Constructors are not static and cannot be. A constructor always builds a new object, so it is tied to instance creation.
Choosing the right kind of member
Ask one question of any piece of data: does this value differ from object to object?
- If it does, make it an instance field. A
Person's name, anOrder's items, and aCounter's id are examples. - If one value is true for the whole class, make it static. Examples are a count of instances created, a default setting, and a mathematical constant.
Ask the same of a behavior: does it need the state of a particular object?
- If it reads or changes an object's fields, make it an instance method.
- If it works only from its parameters, it can be static.
Math.max(a, b)is the classic case.
Common mistakes at this stage
- Making a field static to avoid passing it around. If every
Personshould have a different name,static String namemakes all people share one name. The program compiles and then produces wrong results. - Expecting a static field to reset per object. It never resets as objects come and go. A counter incremented in the constructor goes up for the life of the class, even after objects become unreachable. Garbage collection of objects does not decrement it.
- Reading a static field as if it were set per instance. Code such as
a.shared = 99changes the value for every object and for code that has no object at all. - Assuming a static field belongs to a single run of one method. It outlives every method call. State left in it is visible to the next caller.
Summary of the model
Every member is either object-level or class-level. Object-level members exist once per object, are reached through a reference, and have access to this. Class-level members exist once per class, are reached through the class name, and have no this. The rest of this tutorial follows from that one split: what a static method may touch, how static state is initialized, how static members interact with inheritance, and when shared state becomes a design risk.
Exercise
A class Ticket declares private static int issued = 0; and private final int number;. Its constructor runs issued++; number = issued;. Three Ticket objects are created in a row. What are the three number values, and what does Ticket.issued equal afterwards? Why does each object keep a different number if issued is shared?
Show answer
The numbers are 1, 2, and 3, and issued equals 3. The field issued has one storage location, so each constructor call increments the same value. The field number is an instance field, so each object has its own copy. Each constructor copies the current value of issued into its own number once, and that copy does not change when issued changes later.
Exercise
Given static int shared = 10; and int own = 5; in class Box, and two objects x and y created with new Box(), what do y.own and y.shared show after the statements x.own = 20; and x.shared = 30;? What does Box.shared show?
Show answer
y.own shows 5, because own is an instance field and x and y have separate copies. y.shared shows 30, and Box.shared also shows 30. There is only one shared field, so writing through x changes the single shared value. Writing Box.shared = 30 expresses the same intent more clearly.