What is the difference between a class and an object, and how does the runtime treat them differently?
A class is the description of a kind of thing, and an object is one actual instance of that kind. The class is the blueprint and the object is the house built from it.
public class Main {
public static void main(String[] args) {
Wheel front = new Wheel();
Wheel rear = new Wheel();
Car car = new Car(front, rear);
System.out.println(front == rear); // false, two objects
System.out.println(front == car.front()); // true, the same object
}
}
And how does the runtime treat them differently? The class lives in the class area of the memory, which is shared by every object of that class and by every thread. The object lives in the heap, and each object has its own copy of the fields.
the thing where it lives how many there are
-------------- ----------------- --------------------------
the class the class area one for each class
the object the heap one for each new call
And there is a second difference that is worth knowing about. The class holds the methods and the shape of the data. The object holds the actual values in those fields. So the methods are shared by every object and the values are not.
public class Wheel {
private int diameter;
public Wheel() {
this.diameter = 17;
}
public int diameter() {
return diameter;
}
}
So here the class holds the code and the list of the fields. And each Wheel object holds one diameter value. When you make ten wheels then there is one copy of the code and ten values.
And there is a third thing that is worth knowing about. The new keyword is what makes an object. It asks the runtime to set aside the memory, to run the constructor, and to give back a reference to the new object. The class is not copied at all.
So the rule to remember is this. The class is the shared description and the object is the one piece of data that follows it.
The next two questions in this topic count the objects and give the plain meaning.