Skip to content

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).

1. What is a Class? (The Blueprint 🏗️)

A class is a blueprint that defines:

  • Attributes (variables) → What the object has.
  • Methods (functions) → What the object can do.

Example: A Car Class 🚗

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! 🚗").


2. What is an Object? (A Real Car 🚘)

A class is just a blueprint. To use it, we need to create an object from it!

Example: Creating a Car Object

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
    }
}

Example Output:

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!


3. Why Use OOP? (Benefits 🎯)

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

4. What’s Next?

Now that we understand classes and objects, let’s explore constructors—special methods that help create objects! 🚀

Clone this wiki locally