Imagine you are an architect. You draw a Blueprint for a house. The blueprint isn't a house; you can't live in it, and it doesn't have a physical address. It’s just a set of instructions that says, "A house should have 3 bedrooms, 2 bathrooms, and be painted a certain color."
The Class is the Blueprint. It defines what data (Variables) and what actions (Methods) a specific thing should have.
The Object is the Physical House. Once you use the blueprint to build a house at 123 Maple St, that specific house is an "Instance" of the blueprint. You can build 100 different houses from the same blueprint—each might have a different color or owner, but they all follow the same structure.
The Two Pillars of a Class
Fields (Attributes): These are variables that describe the object (e.g.,
color,model,price).Methods (Behaviors): These are functions that describe what the object can do (e.g.,
drive(),brake(),honk()).
The Code Example
In Java, we usually create a separate class and then use it in our Main class.
// 1. Defining the Blueprint (The Class)
class Car {
// Fields (Attributes)
String brand;
int year;
boolean isElectric;
// Method (Behavior)
void drive() {
System.out.println("The " + brand + " is now zooming down the road!");
}
void displayInfo() {
System.out.println("Car: " + year + " " + brand + " (Electric: " + isElectric + ")");
}
}
// 2. Using the Blueprint (The Main Class)
public class Main {
public static void main(String[] args) {
// Creating the first Object (Instance)
Car myCar = new Car();
myCar.brand = "Tesla";
myCar.year = 2024;
myCar.isElectric = true;
// Creating a second Object (Instance) from the same blueprint
Car friendCar = new Car();
friendCar.brand = "Ford Mustang";
friendCar.year = 1969;
friendCar.isElectric = false;
// Using the methods
myCar.displayInfo();
myCar.drive();
System.out.println("---");
friendCar.displayInfo();
friendCar.drive();
}
}Expected Output:
Car: 2024 Tesla (Electric: true)
The Tesla is now zooming down the road!
---
Car: 1969 Ford Mustang (Electric: false)
The Ford Mustang is now zooming down the road!Before OOP, programming was just a long list of instructions. If you wanted to change how a "Car" worked, you’d have to find every mention of a car in 10,000 lines of code.
With OOP:
Organization: Everything related to a "Car" is inside the
Carclass.Scalability: You can create thousands of "Car" objects easily.
Realism: It allows us to model the real world. Instead of thinking about "bits and bytes," we think about "Users," "Products," and "Messages."
Note on
new: The keywordnewis what tells Java to go into the computer's memory and actually build the object based on the class.