In Java, everything is based around the concept of a class and objects. A class defines what an object is and what it can do. An object is an instance of a class — a specific version of that class that exists in memory.
What is a class?
A class is like a blueprint or template that describes the structure and behaviour of objects. It defines the variables (called fields) and the subprograms (called methods) that belong to the object.
public class Car { String make; String model; int year; void startEngine() { System.out.println("The engine has started."); } }
In this example, the class Car defines three fields and one method.
However, at this stage, no actual car exists — the class is just a definition.
Creating object instances
To use a class, you must create an object instance from it using the
new keyword. Each object has its own copy of the class’s fields.
Car myCar = new Car(); myCar.make = "Toyota"; myCar.model = "Corolla"; myCar.year = 2020; myCar.startEngine();
The engine has started.
Each object created from the same class can have different values for its fields:
Car car1 = new Car(); Car car2 = new Car(); car1.make = "Honda"; car2.make = "Ford"; System.out.println(car1.make); System.out.println(car2.make);
Honda Ford
Constructors
A constructor is a special method used to create and initialise objects. It has the same name as the class and does not have a return type.
public class Car { String make; String model; int year; // Constructor public Car(String make, String model, int year) { this.make = make; this.model = model; this.year = year; } }
When you create a new object, the constructor runs automatically:
Car myCar = new Car("Mazda", "CX-5", 2021);
Using methods
Methods define what actions an object can perform. They are called using the dot (.) operator.
Methods can also access the object’s fields and modify them.
public class Car { String make; int speed; void accelerate(int increase) { speed += increase; System.out.println(make + " is now going " + speed + " km/h"); } } Car car = new Car(); car.make = "Mini"; car.accelerate(20);
Mini is now going 20 km/h
Classes vs objects
| Class | Object |
|---|---|
| A blueprint or template. | A real instance of that blueprint. |
| Defines structure and behaviour. | Stores real data and performs actions. |
| Exists only once in code. | Many objects can be created from one class. |
