Skip to content

Module 2: Object-Oriented Programming (The Blueprint)

📚 Module 2: Object-Oriented Programming (OOP)

Focus: Moving from “Scripts” to “Blueprints.”

Java is the world’s most popular Object-Oriented language. This means we design our code to look like real-world things.


🏗️ Step 1: Classes & Objects (The “Car Factory”)

🧩 The Analogy: The Blueprint vs. The Car

  • The Class: The Blueprint. It’s just a piece of paper that says: “A car has 4 wheels, a color, and a speed.” It’s not a real car yet.
  • The Object: The Real Car that comes off the assembly line. You can touch it, drive it, and paint it red.

In Java:

// The Class (The Blueprint)
public class Car {
    String color;
    int speed;

    void drive() {
        System.out.println("The car is driving!");
    }
}

// The Usage (The Assembly Line)
Car myCar = new Car(); // 'new' is the magic word that builds the object!
myCar.color = "Red";
myCar.drive();

🏗️ Step 2: Encapsulation (The “Remote Control”)

In Java, we don’t want everyone to mess with the “Internal Wires” of our objects. We want to hide them.

🧩 The Analogy: The TV Remote

  • When you want to change the channel, you press a button on the Remote (The Public Method).
  • You don’t open the back of the TV and touch the circuit board (The Private Field).

In Code:

public class User {
    private String password; // PRIVATE: Nobody can see this directly

    // PUBLIC method to change the password
    public void setPassword(String newPass) {
        if (newPass.length() > 8) {
            this.password = newPass;
        }
    }
}

🏗️ Step 3: Inheritance (The “Family Tree”)

Instead of writing the same code over and over, classes can share features.

🧩 The Analogy: The Animal Kingdom

  • Parent (Base Class): Animal (Has a heartbeat, can breathe).
  • Child (Subclass): Dog (Is an Animal, but ALSO barks).
  • Child (Subclass): Bird (Is an Animal, but ALSO flies).

In Java:

public class Dog extends Animal {
    void bark() {
        System.out.println("Woof!");
    }
}

🏗️ Step 4: Polymorphism (The “Smart Tool”)

Polymorphism means “Many Shapes.” It’s the ability of one command to do different things depending on the object.

🧩 The Analogy: The “Speak” Command

If you tell a group of animals to “Speak”:

  • The Dog barks.
  • The Cat meows.
  • The Bird chirps. You didn’t have to give separate instructions; they all “knew” how to speak in their own way.

🥅 Module 2 Review

  1. Class: The blueprint for your data.
  2. Object: The real instance of that blueprint.
  3. Encapsulation: Hiding the “wires” with private and public.
  4. Inheritance: Reusing code via the extends keyword.
  5. Polymorphism: One command, many behaviors.