🧱 Object-Oriented Programming (OOP)

What is OOP?

Object-Oriented Programming (OOP) is a programming paradigm that models real-world entities as “objects” in code. Each object is an instance of a “class,” which serves as a blueprint defining the object’s properties (attributes) and behaviors (methods)

Key Concepts:

  • Class: A template for creating objects, defining attributes and methods
  • Object: An instance of a class with actual values
  • Encapsulation: Bundling data and methods that operate on the data within one unit, and restricting access to some of the object’s components
  • Inheritance: A mechanism where one class can inherit fields and methods from another class
  • Polymorphism: The ability of different classes to be treated as instances of the same class through a common interface
  • Abstraction: Hiding complex implementation details and showing only the necessary features of an object

Example:

// Base class
class Animal {
    String name;
 
    Animal(String name) {
        this.name = name;
    }
 
    void speak() {
        System.out.println(name + " makes a sound.");
    }
}
 
// Derived class
class Dog extends Animal {
    Dog(String name) {
        super(name);
    }
 
    @Override
    void speak() {
        System.out.println(name + " barks.");
    }
}
 
public class Main {
    public static void main(String[] args) {
        Animal generic = new Animal("Creature");
        Dog buddy = new Dog("Buddy");
 
        generic.speak(); // Output: Creature makes a sound.
        buddy.speak();   // Output: Buddy barks.
    }
}

Common Mistakes:

  • Forgetting to use super(): When a subclass constructor doesn’t explicitly call the superclass constructor
  • Accessing private members directly: Violates encapsulation; use getters/setters instead!
  • Overriding methods incorrectly: Not using the @Override annotation can lead to subtle bugs

Further Learning: