No history yet

Object-Oriented Programming

What Is Object-Oriented Programming?

Object-Oriented Programming, or OOP, is a way of thinking about and organizing code. Instead of writing long lists of instructions, you create

objects that model real-world entities and their interactions.

Think about building a car. You don't think about it as one massive chunk of metal and wires. You think about its parts: the engine, the wheels, the steering wheel. Each part has its own job, but they all work together to make the car run.

OOP works the same way. We break down a complex program into smaller, manageable, and reusable pieces called objects. Each object contains its own data (attributes) and behaviors (methods).

This approach is built on four key principles: Encapsulation, Abstraction, Inheritance, and Polymorphism. Let's look at each one.

Encapsulation

Encapsulation means bundling the data and the methods that operate on that data into a single unit, or

to bind together the data and the functions that operate on them so that no other part of the code can access this data except that function.

This principle is all about control and protection. An object should control its own state. Other parts of the program can't just reach in and change an object's data whenever they want. Instead, they have to use the object's public methods to interact with it.

Consider a bank account. You have a balance, but you can't just change it directly. You have to use methods like deposit() or withdraw(). This prevents accidental or invalid changes, like setting your balance to a negative number without a proper transaction.

Here's how that might look in code:

class BankAccount {
  // Private data, can't be accessed directly
  private double balance;

  public BankAccount(double startingBalance) {
    this.balance = startingBalance;
  }

  // Public method to deposit money
  public void deposit(double amount) {
    if (amount > 0) {
      balance += amount;
    }
  }

  // Public method to get the balance
  public double getBalance() {
    return balance;
  }
}

The balance is kept private, protecting it from the outside world. To interact with it, you must use the public deposit and getBalance methods. This bundling of data and methods is encapsulation.

Abstraction

Abstraction means hiding the complex implementation details and showing only the essential features of an object. It's about simplifying reality by modeling classes appropriate to the problem.

Think about driving a car. To make it go faster, you press the gas pedal. You don't need to know about the fuel injectors, the engine cylinders, or the combustion process. All that complexity is hidden from you. You are given a simple interface—the pedal—to achieve your goal.

In programming, abstraction works the same way. We create classes that expose high-level mechanisms for using them, without revealing the intricate details of how they work. This makes our code easier to use and reduces the impact of changes. If an engineer improves the car's engine, you still just press the same gas pedal to accelerate.

Encapsulation bundles data and methods together. Abstraction hides the 'how' and shows only the 'what'.

For example, we could have an abstract Vehicle class that defines what all vehicles must be able to do, without specifying how.

abstract class Vehicle {
  // All vehicles must be able to start
  abstract void start();

  // All vehicles must be able to stop
  abstract void stop();
}

Any class that wants to be a Vehicle, like Car or Motorcycle, must provide its own specific implementation for the start() and stop() methods.

Inheritance

Inheritance is a mechanism where a new class derives properties and behaviors from an existing class. It's all about code reusability and creating relationships between objects. This creates an "is-a" relationship: a Bulldog is a Dog, and a Dog is an Animal.

The class being inherited from is called the parent or superclass. The class that inherits is the child or subclass. The child class can use all the fields and methods of the parent class and can also add its own.

Here, both Car and Motorcycle are types of Vehicle. They might share common attributes like speed and color from the Vehicle class, but each might also have unique features. For instance, a Car has four wheels, while a Motorcycle has two. Inheritance lets us define Vehicle once and reuse its logic for all types of vehicles.

// Parent class
class Animal {
  public void eat() {
    System.out.println("This animal eats food.");
  }
}

// Child class
class Dog extends Animal {
  public void bark() {
    System.out.println("The dog barks.");
  }
}

A Dog object can now both eat() (from Animal) and bark() (its own method).

Polymorphism

Polymorphism, which means "many forms," allows objects of different classes to be treated as objects of a common superclass. It's the ability to perform a single action in different ways.

Let's stick with our Animal example. Suppose we have an Animal class with a method called makeSound(). Different animals make different sounds. A Dog barks, a Cat meows, and a Cow moos. Polymorphism allows us to have different implementations of the makeSound() method for each subclass.

class Animal {
  public void makeSound() {
    System.out.println("Some generic animal sound");
  }
}

class Dog extends Animal {
  @Override
  public void makeSound() {
    System.out.println("Woof woof!");
  }
}

class Cat extends Animal {
  @Override
  public void makeSound() {
    System.out.println("Meow!");
  }
}

Now, we can write code that works with Animal objects without needing to know their specific type at compile time. This makes our code more flexible and decoupled.

Animal myDog = new Dog();
Animal myCat = new Cat();

myDog.makeSound(); // Outputs: Woof woof!
myCat.makeSound(); // Outputs: Meow!

Even though myDog and myCat are both treated as Animal types, the correct makeSound method is called for each one at runtime. That's polymorphism in action.

These four principles are the pillars of object-oriented programming. Understanding them is the first step to designing clean, scalable, and maintainable software.