A class is a blueprint. It says what data (fields) and behaviour (methods) its objects have. An object is one real instance built from that blueprint with new.
class Car {
String model;
int speed;
void accelerate(int by) {
speed += by;
}
}
Car c = new Car(); // object created on the heap
c.model = "Swift";
c.accelerate(20);The variable c is not the object. It is a reference that points to the object. That matters:
Car d = c;creates no new object. Both names now point to the same car, so a change throughdis visible throughc.- Fields you do not set get default values:
0for numbers,falseforboolean,nullfor objects (includingString). Local variables get no default and must be assigned before use.
Each object has its own copy of the instance fields. Two Car objects can have different speeds.
In interviews: "What is the difference between a class and an object?" A class is a logical template and takes no heap memory for its fields; an object is a physical instance with its own state, created at runtime.