Classes, objects and references
Junior Always asked 6 min
On this page
The question
What is the difference between a class and an object in Java?
30-second answer
A class is a blueprint: it declares fields and methods once. An object is one instance of that class, created with new on the heap, with its own copy of the instance fields. Variables do not hold objects; they hold references that point at them. Static members belong to the class and are shared by every object.
Understand it
What new Car("red") does
Step by stepThe JVM (Java Virtual Machine) loads the Car class once, keeping its fields and methods as the blueprint for every Car.
View as text
The line Car c = new Car("red") runs. The drawing has a stack on the left, a heap on the right and the Car class below the heap.
The JVM (Java Virtual Machine) loads the Car class once, keeping its fields and methods as the blueprint for every Car. The class box is highlighted.
new reserves heap memory for one Car object, and the object records which class it belongs to. A dashed box appears in the heap with an arrow to the class.
Every field starts at its default value, so color is null before any constructor code runs. The box reads color = null.
The constructor Car("red") runs and sets color to "red". The box now reads color = "red".
new returns a reference, stored in the variable c on the stack. c points at the object; it is not the object. An arrow leads from c on the stack to the object in the heap.
The line Car c = new Car("red") runs. The drawing has a stack on the left, a heap on the right and the Car class below the heap.
The JVM (Java Virtual Machine) loads the Car class once, keeping its fields and methods as the blueprint for every Car. The class box is highlighted.
new reserves heap memory for one Car object, and the object records which class it belongs to. A dashed box appears in the heap with an arrow to the class.
Every field starts at its default value, so color is null before any constructor code runs. The box reads color = null.
The constructor Car("red") runs and sets color to "red". The box now reads color = "red".
new returns a reference, stored in the variable c on the stack. c points at the object; it is not the object. An arrow leads from c on the stack to the object in the heap.
Takeaway: new allocates an object on the heap, sets default values, runs the constructor and returns a reference; the variable holds that reference, not the object.
One count per object or per class?
CompareEach Counter object has its own count. Three increments touch three copies, so each object reads 1.
View as text
Three Counter objects, a, b and c, each run count++ once. The Counter class is drawn above them.
Instance field: each Counter object has its own count. Three increments touch three copies, so each object reads 1. Every object box shows count = 1 and the class holds nothing.
Static field: the class holds one count shared by all objects. Three increments touch the same copy, so every object reads 3. The class box shows count = 3 and arrows lead from each object up to it.
Three Counter objects, a, b and c, each run count++ once. The Counter class is drawn above them.
Instance field: each Counter object has its own count. Three increments touch three copies, so each object reads 1. Every object box shows count = 1 and the class holds nothing.
Static field: the class holds one count shared by all objects. Three increments touch the same copy, so every object reads 3. The class box shows count = 3 and arrows lead from each object up to it.
Takeaway: An instance field belongs to each object; a static field belongs to the class, so every object shares one copy.
In code
Car a = new Car("red");
Car b = a; // same object, second reference
b.color = "blue";
System.out.println(a.color); // blue
Car copy = new Car(a.color); // a separate objectCounter c = new Counter();
c.increment(); // instance method: changes c's own value
Wrong c.total(); // compiles, but reads like it depends on c
Right Counter.total(); // clear: total() belongs to the classclass Ticket {
static int issued = 0; // one copy, shared by every Ticket
final int number; // one copy per object
Ticket() { number = ++issued; }
}
new Ticket();
new Ticket();
Ticket t = new Ticket();
System.out.println(t.number + " of " + Ticket.issued); // 3 of 3Solve it
Why does every user show the last name entered?
A teammate’s class stores a name per user. They create three users, “Ana”, “Ben” and “Cara”, and print each one’s name. All three print “Cara”. Find the cause and fix it.
- Read the symptom. Every object shows the value written last. When separate objects agree on the newest value, they share one variable.
- Find the shared state.
nameisstatic: one variable for the class, not one per object, so each constructor overwrote it. - Decide where the value belongs. A name describes one user, so it is instance state. Remove
static, and make itprivate finalbecause it never changes. - Check. Three objects now hold three names. Keep
staticfor values that describe the class itself, such as a count or a constant.
class User {
Wrong static String name; // one name for all users
User(String n) { name = n; }
}
class FixedUser {
Right private final String name; // one name per user
FixedUser(String n) { this.name = n; }
String name() { return name; }
}How to answer
- A class defines state and behavior; an object is a runtime instance with its own field values.
newallocates the object on the heap, sets default values, runs the constructor and returns a reference.- A variable of a class type holds a reference, so two variables can point at the same object.
- Static members belong to the class; instance members belong to each object.
Common mistakes
- Saying a variable contains the object itself, which hides why assigning it copies only the reference.
- Saying objects are created when the class is loaded, or using "class" and "object" as synonyms.
Follow-up questions
What happens, step by step, when you write new Car("red")?
The JVM loads the Car class if it is not loaded yet, allocates heap memory for the object, sets every field to its default value, runs the constructor, and returns a reference to the new object.
- Class loading happens once, on first use of the class.
- Fields hold default values before the constructor body runs.
newreturns a reference, which the variable stores.
What is the difference between static and instance members?
An instance member belongs to each object: every object has its own copy of an instance field, and instance methods run on one object through this. A static member belongs to the class: one copy of a static field is shared by all objects, and static methods run without any object.
- Instance field: one copy per object.
- Static field: one copy per class, shared by every object.
- Static methods have no
this, so they cannot read instance fields directly.
See it in the infographic: One count per object or per class?
After Car b = a; and b.color = "blue";, what is a.color, and why?
It is "blue". Car b = a copies the reference, not the object, so a and b point at the same Car. A change made through b is visible through a.
- Assignment copies the reference, never the object.
- Both variables now reach one object.
- Create a new object explicitly when you need an independent copy.
Car a = new Car("red");
Car b = a;
b.color = "blue";
System.out.println(a.color); // blue Does calling a static method through a null reference throw a NullPointerException?
No. The compiler binds a static call to the variable's declared type, so c.total() with c null runs as Counter.total(). An instance method called through the same null reference throws NullPointerException. Call static methods through the class name to avoid the confusion.
- Static calls use the variable's declared type, not the object.
- Instance calls need an object and throw on null.
- Write
Counter.total(), notc.total().
Counter c = null;
c.total(); // runs: compiled as Counter.total()
c.value(); // NullPointerException See it in the infographic: One count per object or per class?
Why can't a static method read an instance field directly?
A static method runs without an object, so there is no this to say whose field to read. Three Counter objects have three count fields; the static method must be handed one of the objects, for example as a parameter.
- Static methods have no
this. - Instance fields exist once per object, so the method must name the object.
- Pass the object in, or make the method an instance method.
See it in the infographic: One count per object or per class?
Where does the JVM keep the information about a class?
In the method area, which HotSpot implements as Metaspace outside the heap since Java 8. It holds each loaded class's metadata and method code, and every object's header points back to its class.
What values do fields have before the constructor runs?
Their defaults: 0 for numbers, false for boolean and null for references. Local variables get no default, so the compiler rejects reading one before it is assigned.
Is a Java reference the same as a C pointer?
It plays the same role, but Java hides the address: there is no pointer arithmetic, and the garbage collector may move the object while the reference stays valid.
Check yourself
Show answers
- red: Incorrect. Car b = a copies the reference, so a and b share one object.
- blue: Correct. Both variables point at the same object, which was changed through b.
- It does not compile: Incorrect. Assigning one reference to another of the same type is legal.
Show answers
- 1, 1 and 1: Incorrect. That would be an instance field, with one copy per object.
- 3, 3 and 3: Correct. A static field has one copy, incremented three times and read by every object.
- 1, 2 and 3: Incorrect. All objects read the same single copy after the three increments.
Show answers
- 0 and null: Correct. Fields start at their default values before the constructor body sets them.
- Nothing until assigned: Incorrect. Fields always get defaults; only local variables must be assigned before use.
- 0 and an empty string: Incorrect. References default to null, never to an empty string.