ProLesson 4.1Beginner3 min readUpdated 30 October 2026
Classes and objects
The heart of Java. Learn what a class and an object are, how to give objects state and behaviour, and what really happens when you write new.
Object-oriented programming (OOP) means organising code around things: a customer, an order, a bank account. Java is built on two ideas:
- A class is a blueprint. It describes what data a thing has and what it can do.
- An object is one real thing built from that blueprint.
One Car class, many car objects: a red one, a blue one, each with its own number plate.
01Your first class
Shop.java
class Product {
// fields: the object's data (state)
String name;
double price;
int stock;
// methods: what the object can do (behaviour)
boolean isAvailable() {
return stock > 0;
}
void sell(int quantity) {
stock -= quantity;
}
}
public class Shop {
public static void main(String[] args) {
Product book = new Product(); // create an object
book.name = "Clean Code";
book.price = 499;
book.stock = 2;
Product pen = new Product(); // a second, separate object
pen.name = "Gel pen";
pen.price = 20;
book.sell(2);
System.out.println(book.name + " available? " + book.isAvailable());
System.out.println(pen.name + " available? " + pen.isAvailable());
}
}Clean Code available? false Gel pen available? false
book and pen are two objects of the same class, and each has its own fields. Changing book.stock doesn't touch pen.stock. (The pen's stock was never set, so it's the default, 0.)
Loading the rest of the lesson…