Classes & Objects (OOP)
Java is an object-oriented language, which means programs are built around classes and objects. This is one of the most important ideas in the whole language, so let's build it up slowly with a real example.
Class vs Object
| Term | What it is |
|---|---|
| Class | A blueprint or template. It describes what properties and behaviors something will have, but isn't a real thing by itself. |
| Object | An instance of a class — a real, concrete thing created from that blueprint, with its own actual values. |
Think of a class like an architect's blueprint for a house, and each object like an actual house built from that blueprint. You can build many houses (objects) from one blueprint (class), and each one can be painted a different color.
Defining a Class
A class groups together fields (also called properties — the data it holds) and methods (the behavior it can perform).
public class Car {
// fields (properties)
String brand;
int speed;
// method (behavior)
void drive() {
System.out.println(brand + " is driving at " + speed + " km/h");
}
}
Creating an Object with new
The new keyword creates an actual object from a class, allocating memory for it. You then access its fields and methods using dot notation.
public class Main {
public static void main(String[] args) {
Car myCar = new Car(); // create an object
myCar.brand = "Toyota"; // set a field
myCar.speed = 120;
myCar.drive(); // call a method: Toyota is driving at 120 km/h
}
}
Breaking it down:
Car myCar = new Car();—Caris the type,myCaris the variable name, andnew Car()actually builds the object.myCar.brandandmyCar.speed— dot notation accesses fields on a specific object.myCar.drive()— dot notation also calls methods on a specific object.
Objects Are Independent
Each object created from a class has its own copy of the fields. Changing one object's fields has no effect on any other object made from the same class.
Car car1 = new Car();
car1.brand = "Toyota";
car1.speed = 120;
Car car2 = new Car();
car2.brand = "Honda";
car2.speed = 100;
car1.drive(); // Toyota is driving at 120 km/h
car2.drive(); // Honda is driving at 100 km/h - unaffected by car1
car1 and car2 are two completely separate objects in memory. They share the same blueprint (Car) but hold different data.