Object‐Oriented Design Principles - EduardoMSU/OOP-2143 GitHub Wiki

Object-Oriented Design Principles

Object-Oriented Design (OOD) is centered around several core principles that guide the creation of software systems using object-oriented programming (OOP). These principles help ensure that systems are modular, flexible, and easy to maintain. The most important OOD principles are:


Key OOD Principles

Principle Description
Encapsulation The bundling of data and methods that operate on that data into a single unit or class. It hides the internal state of an object and only exposes necessary functionality through public methods.
Abstraction The process of hiding the complex reality while exposing only the essential parts. It allows the programmer to focus on high-level operations rather than the specifics of implementation.
Inheritance A mechanism by which one class can inherit the attributes and methods from another class. This helps in creating hierarchical relationships and promoting code reuse.
Polymorphism The ability of different classes to respond to the same method in a way that is specific to their class. It allows objects of different classes to be treated as objects of a common superclass.

Principles Explained

1. Encapsulation

  • Definition: Encapsulation is the technique of restricting access to the internal state of an object, so that its state can only be modified through defined methods.
  • Benefits:
    • Protects the integrity of an object’s data.
    • Simplifies interaction with objects.
    • Allows control over how an object's data is accessed or modified.

Example in C++

#include <iostream>
using namespace std;

class BankAccount {
private:
    double balance;  // Private variable

public:
    // Constructor
    BankAccount(double initialBalance) : balance(initialBalance) {}

    // Getter for balance (public method)
    double getBalance() {
        return balance;
    }

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

    // Method to withdraw money (public method)
    void withdraw(double amount) {
        if (amount > 0 && amount <= balance) {
            balance -= amount;
        }
    }
};

int main() {
    BankAccount account(1000);
    account.deposit(500);
    cout << "Balance: " << account.getBalance() << endl;

    return 0;
}
⚠️ **GitHub.com Fallback** ⚠️