What is the difference between a class and an object in Java, and how do you tell them apart in code?
A class is the blueprint, and an object is one thing that was built from that blueprint.
The class describes what every one of its objects will have and what every one of them will be able to do. It holds the names of the fields, the methods, the constructor, and the rules about who may use them. The class itself is not a thing that exists in the running program in the same way that an object does.
An object is a real instance. It has its own copy of the data, its own place in memory, and its own identity. Two objects built from the same class have the same shape and separate data.
public class Main {
public static void main(String[] args) {
// The class is the blueprint. The object is the thing built from it.
Car car = new Car("Hatch", 2020);
Car other = new Car("Saloon", 2021);
System.out.println("car : " + car.describe());
System.out.println("other : " + other.describe());
// The class is a value too, and you can ask for it.
System.out.println("the class of a car : " + car.getClass().getName());
System.out.println("the class of a car : " + Car.class.getName());
}
}
class Car {
private final String body;
private final int year;
Car(String body, int year) {
this.body = body;
this.year = year;
}
String describe() {
return body + " from " + year;
}
}
So how do you tell them apart in code? The word new is the marker. Everything before it is a type and everything after it is an object being created. The line Car car = new Car("Hatch", 2020); says that car is a variable of the type Car, and that it now points at a new object of that type.
You can also ask an object at run time what class it came from, and the method getClass gives you that answer. The method getName gives you the full name including the package, and the method getSimpleName gives you just the class name.
The next question in this topic counts how many objects a single line of code really makes.