[!NOTE] Until now, you've written procedural code—a simple list of instructions executed from top to bottom. Java was built from the ground up for a different paradigm: Object-Oriented Programming (OOP).
What is OOP?
OOP is a methodology that attempts to map software directly to real-world entities.
Instead of treating your application as a chaotic mix of variables (userName, userAge) and standalone functions (login(), logout()), OOP bundles related data and behaviors together into structured Objects.
The Blueprint vs The Reality
Consider a Car factory. You don't just randomly weld metal together. You start with an engineering Blueprint. The blueprint defines what a car should have (color, engine type, speed) and what it should do (drive, brake, honk).
In Java:
- The Class is the blueprint.
- The Object (or Instance) is the actual car that rolls off the assembly line.
// 1. We create the Blueprint (Class)
public class Car {
// Attributes (State)
String color;
int currentSpeed;
// Methods (Behavior)
void drive() {
currentSpeed = 60;
System.out.println("The car is driving!");
}
}
Once the blueprint exists, we can use it to stamp out thousands of unique Objects in the main method execution.
public class Main {
public static void main(String[] args) {
// 2. We build the physical car (Object) from the blueprint!
Car myVolvo = new Car();
myVolvo.color = "Red";
Car myBMW = new Car();
myBMW.color = "Black";
// 3. We tell the object to perform its behavioral action
myVolvo.drive();
}
}
Why Use OOP?
- Faster Execution and Maintenance: Finding bugs is easier when all logic related to a "User" is firmly locked inside a single
User.javafile, rather than scattered across 50 random functions. - DRY (Don't Repeat Yourself): You can build a
Vehicleclass and haveCar,Truck, andMotorcycleautomatically inherit all of its logic without rewriting code. - Security: You can hide sensitive data (like
userPassword) inside an object and strictly control how outside code interacts with it.