Video in progress

What is the difference between a class and an object?

A class is a template or blueprint: it describes which fields and methods there will be. An object is a concrete instance created from that blueprint with new on the heap, and its fields hold its own values.

📖 Answer

Think of a house blueprint and the houses built from it. There is one blueprint and many houses, each with its own color and owner.

public class Car {
    private final String model;
    private int speed;

    public Car(String model) { this.model = model; }

    public void accelerate(int delta) { speed += delta; }
}

Car a = new Car("Cobalt");   // the first object
Car b = new Car("Malibu");   // the second object
a.accelerate(40);            // b's speed stays 0

In practice the difference looks like this:

  • a class is compiled into a .class file and loaded into the JVM once;
  • objects are created at runtime, and there can be any number of them;
  • a static field belongs to the class, so there is one for all objects; a regular field is separate in each object.

In an interview, "an object is an instance of a class" is enough, but if you add the memory side (the object is on the heap, the reference is a variable on the stack), the answer gets stronger.