2 min read

Object Oriented Programming (OOP)

Object Oriented Programming is a programming paradigm based on the concept of "objects", which can contain data (attributes) and code (methods). It aims to structure programs so that properties and behaviors are bundled into individual objects.

1. Classes and Objects

  • Class: A blueprint or template for creating objects. It defines the properties and behaviors.
  • Object: An instance of a class.
# Python Example
class Dog:
    def __init__(self, name):
        self.name = name

    def bark(self):
        return "Woof!"

my_dog = Dog("Buddy") # Object creation
print(my_dog.name)    # Accessing attribute

2. Encapsulation

Encapsulation is the bundling of data and methods that operate on that data within a single unit (class), and restricting access to some of the object's components.

  • Public: Accessible from anywhere.
  • Private: Accessible only within the class.
// Java Example
public class BankAccount {
    private double balance; // Private variable

    public void deposit(double amount) {
        if (amount > 0) {
            balance += amount;
        }
    }
}

3. Inheritance

Inheritance allows a class (Child) to derive attributes and methods from another class (Parent). This promotes code reuse.

// JavaScript (ES6) Example
class Animal {
    eat() {
        console.log("Eating...");
    }
}

class Cat extends Animal {
    meow() {
        console.log("Meow");
    }
}

let kitty = new Cat();
kitty.eat(); // Inherited method

4. Polymorphism

Polymorphism allows objects of different classes to be treated as objects of a common superclass. It often involves method overriding (redefining a parent method in a child class).

5. Abstraction

Abstraction involves hiding complex implementation details and showing only the necessary features of an object. This is often achieved using Abstract Classes or Interfaces.

programming/common-syntax programming/functions-and-scope