Object-Oriented Programming (OOP) is a foundational paradigm in modern software engineering. It helps developers design applications with modular, reusable, and maintainable code. OOP is built on four core pillars:
- Encapsulation
- Abstraction
- Inheritance
- Polymorphism
Let's go deep into each one with detailed Java code, real-life analogies, and real-world use cases.
1. Encapsulation
Definition:
Encapsulation is the process of wrapping data (variables) and methods that operate on the data into a single unit (class). It restricts direct access to some of the object's components, which is a means of preventing unintended interference and misuse.
Real-world Analogy:
Think of a bank ATM. You interact with the interface, not the internal wires or database.
Java Code:
public class BankAccount {
private String accountNumber;
private double balance;
public BankAccount(String accountNumber, double initialBalance) {
this.accountNumber = accountNumber;
this.balance = initialBalance;
}
// Getter for account number
public String getAccountNumber() {
return accountNumber;
}
// Getter and setter for balance
public double getBalance() {
return balance;
}
public void deposit(double amount) {
if (amount > 0) {
balance += amount;
}
}
public boolean withdraw(double amount) {
if (amount > 0 && amount <= balance) {
balance -= amount;
return true;
}
return false;
}
}
Use Case:
- Used in financial systems, user profiles, and healthcare records to protect sensitive data.
2. Abstraction
Definition:
Abstraction means hiding complex implementation details and showing only essential features of an object.
Real-world Analogy:
A car dashboard shows you the speed, fuel level, etc., but hides the internal combustion mechanics.
Java Code:
Interface-based Abstraction:
interface PaymentMethod {
void pay(double amount);
}
class CreditCardPayment implements PaymentMethod {
public void pay(double amount) {
System.out.println("Paid " + amount + " using Credit Card.");
}
}
class PayPalPayment implements PaymentMethod {
public void pay(double amount) {
System.out.println("Paid " + amount + " using PayPal.");
}
}
public class ShoppingCart {
public void checkout(PaymentMethod paymentMethod, double amount) {
paymentMethod.pay(amount);
}
public static void main(String[] args) {
ShoppingCart cart = new ShoppingCart();
cart.checkout(new CreditCardPayment(), 150.00);
cart.checkout(new PayPalPayment(), 200.00);
}
}
Use Case:
- Enables plugin architecture
- API design (e.g., Spring Boot uses abstraction for service layers)
3. Inheritance
Definition:
Inheritance allows one class (child) to acquire properties and behavior (methods) from another class (parent).
Real-world Analogy:
A child inherits traits from parents.
Java Code:
class Employee {
protected String name;
protected int id;
public Employee(String name, int id) {
this.name = name;
this.id = id;
}
public void work() {
System.out.println(name + " is working.");
}
}
class Manager extends Employee {
private int teamSize;
public Manager(String name, int id, int teamSize) {
super(name, id);
this.teamSize = teamSize;
}
public void conductMeeting() {
System.out.println(name + " is conducting a meeting with " + teamSize + " members.");
}
}
public class Office {
public static void main(String[] args) {
Manager manager = new Manager("Alice", 101, 5);
manager.work();
manager.conductMeeting();
}
}
Use Case:
- Create a class hierarchy:
Vehicle -> Car, Truck
- Code reuse across similar objects
4. Polymorphism
Definition:
Polymorphism means "many forms". It allows one method or interface to act differently based on the object.
Types:
- Compile-time Polymorphism (Method Overloading)
- Runtime Polymorphism (Method Overriding)
Java Code:
A. Compile-time Polymorphism:
class Calculator {
int add(int a, int b) {
return a + b;
}
double add(double a, double b) {
return a + b;
}
int add(int a, int b, int c) {
return a + b + c;
}
}
B. Runtime Polymorphism:
class Animal {
public void makeSound() {
System.out.println("Some generic sound");
}
}
class Dog extends Animal {
public void makeSound() {
System.out.println("Dog barks");
}
}
class Cat extends Animal {
public void makeSound() {
System.out.println("Cat meows");
}
}
public class Zoo {
public static void main(String[] args) {
Animal myAnimal = new Dog();
myAnimal.makeSound(); // Output: Dog barks
myAnimal = new Cat();
myAnimal.makeSound(); // Output: Cat meows
}
}
Use Case:
- Spring framework beans, which implement the same interface
- Event handling in GUIs
Summary Table
Pillar | Keyword/Tool | Description | Real-world Example |
---|---|---|---|
Encapsulation | private, getters/setters | Protect internal state | ATM/bank account |
Abstraction | interface, abstract class | Hide complexity, expose behavior | TV remote, car dashboard |
Inheritance | extends | Reuse code from parent class | Parent-child traits |
Polymorphism | overloading, overriding | Same method, different behavior | Animal sound variations |
Real-world Project Use Case: E-Commerce Platform
- Encapsulation: Hide user password and order total
-
Abstraction: Define
PaymentMethod
interface for CreditCard/UPI/Wallet -
Inheritance:
User -> Admin, Vendor, Customer
-
Polymorphism:
applyDiscount()
overridden inSeasonalProduct
,ClearanceProduct
OOP Interview Questions
- What's the difference between encapsulation and abstraction?
- Can you achieve abstraction without using interfaces?
- Explain real-world use of inheritance and how it affects design.
- Give a code example of runtime polymorphism in Spring Boot.
- Why prefer composition over inheritance in microservices?
Mastering these OOP pillars leads to better design patterns, solid architecture, and cleaner code.
Would you like this content turned into a Markdown blog post with embedded images and emoji support?
Top comments (0)