TechnicalEasy OOP & Design
What are the four pillars of object-oriented programming?
Asked for Backend Developer, Full-Stack Developer, Mobile Developer
Why they ask this: Asked in almost every fresher interview in Nepal; a clear answer with examples stands out.
Answer
- Encapsulation: keep data and the methods that use it together, and hide internal state behind a public interface (
privateproperties, public methods). - Abstraction: expose what an object does and hide how it does it, for example a
PaymentGatewayinterface with acharge()method. - Inheritance: a class reuses and extends another class (
class Admin extends User). - Polymorphism: different classes are used through the same interface, and each behaves in its own way.
php
interface PaymentGateway
{
public function charge(int $amountInPaisa): bool;
}
final class EsewaGateway implements PaymentGateway
{
public function charge(int $amountInPaisa): bool { /* call eSewa */ return true; }
}
final class KhaltiGateway implements PaymentGateway
{
public function charge(int $amountInPaisa): bool { /* call Khalti */ return true; }
}
function checkout(PaymentGateway $gateway): void
{
$gateway->charge(150000); // polymorphism: works with either gateway
}Can you explain this in your own words?