What Are the 4 Main Principles of Object-Oriented Programming (OOP)? [With Examples]
Category: Oop
Object-Oriented Programming (OOP) is built on four key principles that help in writing modular, scalable, and maintainable code. Whether you're coding in PHP, Java, or any OOP language, these concepts remain the same.
✅ 1. Encapsulation – Protecting Data with Boundaries
Definition: Encapsulation is the practice of restricting direct access to the internal state of an object and only allowing it through public methods.
Example in PHP:
class User {
private $name;
public function setName($name) {
$this->name = $name;
}
public function getName() {
return $this->name;
}
}
✅ Benefits: Enhances security, improves code maintainability, and reduces complexity.
✅ 2. Abstraction – Hiding Complex Details
Definition: Abstraction means showing only essential information while hiding the background implementation details. This allows users to interact with objects without needing to understand the internal workings.
Example in PHP:
abstract class Animal {
abstract public function makeSound();
}
class Dog extends Animal {
public function makeSound() {
return "Bark";
}
}
✅ Benefits: Reduces complexity and focuses on what an object does, not how.
✅ 3. Inheritance – Reusing Code Across Classes
Definition: Inheritance allows a class (called child or subclass) to inherit properties and methods from another class (called parent or superclass).
Example in PHP:
class Vehicle {
public function move() {
return "Vehicle is moving";
}
}
class Car extends Vehicle {
// Car now has access to move() method
}
✅ Benefits: Promotes code reuse and logical hierarchy.
✅ 4. Polymorphism – One Interface, Many Forms
Definition: Polymorphism allows different classes to implement the same method in different ways, enabling method overriding and interface implementation.
Example in PHP:
interface Shape {
public function draw();
}
class Circle implements Shape {
public function draw() {
return "Drawing Circle";
}
}
class Square implements Shape {
public function draw() {
return "Drawing Square";
}
}
✅ Benefits: Makes code flexible and extendable.