-
Notifications
You must be signed in to change notification settings - Fork 0
Object‐Oriented Programming (OOP) – Making Java More Powerful
Seanti edited this page Mar 24, 2025
·
1 revision
Java is an object-oriented programming (OOP) language, which means we organize code into objects that interact with each other.
Think of OOP like a blueprint for a house:
- A blueprint (class) defines how a house should look.
- A house built from the blueprint (object) is a real thing you can live in.
- Each house (object) follows the blueprint (class) but can have different colors or sizes (properties).
A class is a blueprint that defines:
- Attributes (variables) → What the object has.
- Methods (functions) → What the object can do.
public class Car {
String brand; // Car's brand
int speed; // Car's speed
// Method: Make the car honk
void honk() {
System.out.println("Beep beep! 🚗");
}
}➡️ This Car class has:
✔️ A brand (e.g., "Toyota")
✔️ A speed (e.g., 120 km/h)
✔️ A honk() method (prints "Beep beep! 🚗").
A class is just a blueprint. To use it, we need to create an object from it!
public class Main {
public static void main(String[] args) {
Car myCar = new Car(); // Create a new Car object
myCar.brand = "Toyota"; // Assign a brand
myCar.speed = 120; // Set speed
System.out.println("My car is a " + myCar.brand);
System.out.println("It can go " + myCar.speed + " km/h!");
myCar.honk(); // Call the honk() method
}
}My car is a Toyota
It can go 120 km/h!
Beep beep! 🚗
➡️ We created an object (myCar) based on the Car class and used its properties and methods!
| OOP Concept | What It Does | Example |
|---|---|---|
| Encapsulation | Hides details, only allows necessary access | Car’s engine is hidden, but you can drive |
| Inheritance | Allows a class to get properties from another | A SportsCar can inherit from Car
|
| Polymorphism | Same method, different behavior | A car honks "Beep", a truck honks "HOOOONK"
|
| Abstraction | Hides complexity, shows only what’s needed | A phone hides circuits, only shows buttons |
Now that we understand classes and objects, let’s explore constructors—special methods that help create objects! 🚀