Object-Oriented Fundamentals
Object-Oriented Programming (OOP) is a programming paradigm based on the concept of “objects,” which can contain data and code. Data in the form of fields (attributes or properties), and code in the form of procedures (methods).
The four pillars of OOP are Abstraction, Encapsulation, Inheritance, and Polymorphism.
1. Abstraction
Abstraction is the concept of hiding the internal details and showing only the functionality. It helps in reducing programming complexity and effort.
C++ Example of Abstraction
In C++, we use classes to provide abstraction.
#include <iostream>
using namespace std;
class CoffeeMachine {
public:
void makeCoffee() {
boilWater();
brewBeans();
cout << "Coffee is ready!" << endl;
}
private:
void boilWater() { cout << "Boiling water..." << endl; }
void brewBeans() { cout << "Brewing beans..." << endl; }
};
int main() {
CoffeeMachine myMachine;
myMachine.makeCoffee(); // User only knows how to make coffee, not the internals.
return 0;
}
2. Encapsulation
Encapsulation is the bundling of data with the methods that operate on that data. It restricts direct access to some of the object’s components, which is a means of preventing accidental interference and misuse of the data.
Java Example of Encapsulation
public class BankAccount {
private double balance; // Data is hidden
public void deposit(double amount) {
if (amount > 0) balance += amount;
}
public double getBalance() {
return balance;
}
}
3. Inheritance
Inheritance is a mechanism in which one object acquires all the properties and behaviors of a parent object. it represents the IS-A relationship.
Python Example of Inheritance
class Animal:
def speak(self):
pass
class Dog(Animal):
def speak(self):
return "Woof!"
class Cat(Animal):
def speak(self):
return "Meow!"
4. Polymorphism
Polymorphism allows objects of different types to be treated as objects of a common base type. The most common use is when a parent class reference is used to refer to a child class object.
Polymorphism in Action (Java)
Animal myDog = new Dog();
Animal myCat = new Cat();
Animal[] animals = {myDog, myCat};
for (Animal a : animals) {
System.out.println(a.speak()); // Different behavior for different types
}
Why OOP?
- Modularity: Code can be written and maintained independently.
- Information Hiding: Security and reduced side effects.
- Reusability: Through inheritance and composition.
- Pluggability: Polymorphism allows for easily swapping components.
Understanding these fundamentals is the first step toward Object-Oriented Analysis and Design (OOAD), where we model complex real-world systems into these structures.