Skip to lesson

The Four Pillars of OOP with Your Own Examples

The first question in most Java interviews is "explain the four pillars of OOP". The interviewer is checking whether you give your own example and can separate encapsulation from abstraction, not whether you remember a textbook line.

One line and one example for each pillar

The four pillars of OOP are encapsulation, inheritance, polymorphism and abstraction: four ideas that keep object-oriented code safe to change, easy to reuse and simple to use.

Every pillar needs three things in an answer: a one-line definition, your own class names, and why it helps. This program uses all four in about forty lines.

Example 1 · All four pillars in one small program

FourPillars.javaJava
import java.util.List;
interface Payment {    String pay(int amount);}
class Wallet {                                        // encapsulation: guarded state    private int balance;
    Wallet(int balance) {        this.balance = balance;    }
    boolean debit(int amount) {        if (amount <= 0 || amount > balance) {            return false;        }        balance -= amount;        return true;    }
    int getBalance() {        return balance;    }}
class UpiPayment implements Payment {                 // inheritance of type    private final Wallet wallet;
    UpiPayment(Wallet wallet) {        this.wallet = wallet;    }
    public String pay(int amount) {                   // polymorphism: own version        return wallet.debit(amount) ? "UPI paid Rs " + amount : "UPI failed";    }}
class CashPayment implements Payment {    public String pay(int amount) {        return "Cash received Rs " + amount;    }}
public class FourPillars {    public static void main(String[] args) {        Wallet wallet = new Wallet(300);        List<Payment> payments = List.of(new UpiPayment(wallet), new CashPayment(), new UpiPayment(wallet));        for (Payment p : payments) {            System.out.println(p.pay(200));        }        System.out.println("Wallet balance: Rs " + wallet.getBalance());    }}
Output
UPI paid Rs 200
Cash received Rs 200
UPI failed
Wallet balance: Rs 100

What this code does

  • Payment is the abstraction; Wallet encapsulates its balance so it can never go negative; the two classes implement Payment; and the loop shows polymorphism, one call with different behaviour.
  • The second UPI payment fails because the wallet refuses the debit. No outside code could set the balance directly, which is the point of encapsulation.

Encapsulation: private data changed only through methods that enforce rules (BankAccount.withdraw refuses to go negative). Inheritance: a class reuses and extends another with extends (SavingsAccount extends BankAccount). Polymorphism: one call, different behaviour per object (p.pay(500)). Abstraction: show what, hide how (a Payment interface).

Must know:

  • encapsulation protects state; abstraction hides implementation
  • polymorphism needs a common supertype: a parent class or an interface

Encapsulation vs abstraction: the classic confusion

Abstraction means showing only what an object can do and hiding how it does it, usually behind an interface or an abstract class. Callers use the contract and never see the implementation.

Candidates mix these two up because both "hide" something. The program keeps one interface for abstraction and one private map for encapsulation.

Example 2 · Encapsulation and abstraction side by side

EncapVsAbstraction.javaJava
interface MarksStore {                                // abstraction: callers see only this    void record(String roll, int marks);    double average();}
class InMemoryMarksStore implements MarksStore {    private final java.util.Map<String, Integer> marks = new java.util.HashMap<>();   // encapsulated data
    public void record(String roll, int value) {        if (value < 0 || value > 100) {               // encapsulation: rule enforced here            throw new IllegalArgumentException("Marks must be 0-100: " + value);        }        marks.put(roll, value);    }
    public double average() {        return marks.values().stream().mapToInt(Integer::intValue).average().orElse(0);    }}
public class EncapVsAbstraction {    public static void main(String[] args) {        MarksStore store = new InMemoryMarksStore();        store.record("CS01", 78);        store.record("CS02", 92);        try {            store.record("CS03", 120);        } catch (IllegalArgumentException e) {            System.out.println(e.getMessage());        }        System.out.println("Average: " + store.average());    }}
Output
Marks must be 0-100: 120
Average: 85.0

What this code does

  • Abstraction: main only knows MarksStore; it could be switched to a database-backed store without changing main.
  • Encapsulation: the map is private and record rejects marks outside 0 to 100, so the data can never become invalid.

Encapsulation hides an object's data: fields are private, and methods guard every change. Abstraction hides implementation: callers see only a contract, such as an interface method, not how it works.

A quick test: encapsulation answers "who can change this data, and how?"; abstraction answers "what can I ask this thing to do?". One class can show both: a UpiPayment keeps its transaction log private (encapsulation) and is used through Payment (abstraction).

Find the bug

Spot the weak line

Tap the line that breaks the idea.

Which line breaks encapsulation?

Round 1 of 3

Compile-time vs runtime polymorphism

Polymorphism means one call can behave differently depending on the object. Overloading is chosen by the compiler (compile time); overriding is chosen by the JVM from the actual object (run time).

Overloading and overriding are both called polymorphism, but the compiler decides one and the JVM decides the other. The program shows both, plus two things that are not polymorphic.

Example 3 · Overloading, overriding, and fields are not polymorphic

PolymorphismKinds.javaJava
class Notifier {    String channel = "generic";
    String send(String msg) {        return "Notify: " + msg;    }
    String send(String msg, int times) {        return send(msg) + " x" + times;    }
    static String kind() {        return "Notifier";    }}
class SmsNotifier extends Notifier {    String channel = "sms";                           // hides the parent field
    @Override    String send(String msg) {                         // override: run-time choice        return "SMS: " + msg;    }
    static String kind() {                            // hides, does not override        return "SmsNotifier";    }}
public class PolymorphismKinds {    public static void main(String[] args) {        Notifier n = new SmsNotifier();        System.out.println(n.send("Fee due"));        System.out.println(n.send("Exam tomorrow", 2));        System.out.println(n.channel);        System.out.println(((SmsNotifier) n).channel);        System.out.println(Notifier.kind() + " / " + SmsNotifier.kind());    }}
Output
SMS: Fee due
SMS: Exam tomorrow x2
generic
sms
Notifier / SmsNotifier

What this code does

  • send(String) is overridden, so the object's version (SMS) runs, even when called from inside the parent's overloaded send(String, int).
  • The field channel is chosen by the reference type: n.channel is generic until you cast. Static methods are also chosen by type: method hiding, not overriding.

Compile-time polymorphism is method overloading: the same name with different parameter lists. Runtime polymorphism is method overriding, also called dynamic method dispatch.

Only instance methods are polymorphic. Fields and static methods are chosen by the declared type of the reference, a favourite trick question: Parent p = new Child(); p.name reads the parent's field.

Predict the output

Which method runs?

Predict the exact output, then check the reason.

Round 1 of 3

A parent reference holds a child object. Fields and methods are both used.

class P {
String tag = "P";
String who() { return "P"; }
}
class C extends P {
String tag = "C";
String who() { return "C"; }
}
public class Round1 {
public static void main(String[] args) {
P p = new C();
System.out.println(p.tag + p.who());
}
}

Types of inheritance and the diamond problem

The diamond problem is the ambiguity that arises when a class inherits the same method from two parents that both inherit from one grandparent. Java avoids it for classes by allowing only one superclass.

Java classes support single, multilevel and hierarchical inheritance. Multiple inheritance of classes does not compile. The picture and the code show why, and how interfaces give a safe alternative.

The diamond problem. Phone and Camera both extend Device, which has int battery = 100. If SmartPhone could extend both Phone and Camera, it would reach Device by two paths, and nobody could say whether it holds one battery or two. Java does not allow it for classes.

Example 4 · Inheritance types and the diamond

Text
Single         Multilevel          Hierarchical          Multiple (classes: NOT allowed)  A              A                     A                    A       B  |              |                    / \                    \     /  B              B                   B   C                     C        class C extends A, B   -> compile error                 |                 CThe diamond:          A  show()                     / \       show() B         C show()                     \ /                      D   which show()?Java's answer: one superclass only; many interfaces allowed.Two conflicting default methods -> D must override show() and may pick B.super.show().
Summary
Single, multilevel, hierarchical: yes. Multiple classes: no (diamond). Multiple interfaces: yes.

What this code does

  • Draw the diamond when asked "why no multiple inheritance?"; it shows the ambiguity in one picture.
  • Interfaces can still clash on default methods, but the compiler then forces the class to resolve it explicitly, so the ambiguity never reaches run time.

Example 5 · Multiple inheritance of type through interfaces

DiamondFix.javaJava
interface Payable {    default String describe() {        return "can pay";    }}
interface Refundable {    default String describe() {        return "can refund";    }}
class UpiPay implements Payable, Refundable {    @Override    public String describe() {                        // required: both parents give describe()        return "UPI: " + Payable.super.describe() + " and " + Refundable.super.describe();    }}
public class DiamondFix {    public static void main(String[] args) {        UpiPay upi = new UpiPay();        Payable p = upi;        Refundable r = upi;        System.out.println(upi.describe());        System.out.println(p instanceof Refundable);        System.out.println(r.describe());    }}
Output
UPI: can pay and can refund
true
UPI: can pay and can refund

What this code does

  • UpiPay is both a Payable and a Refundable: multiple inheritance of type. Without the override, javac reports that the class inherits unrelated defaults for describe().
  • Payable.super.describe() calls one specific parent's default, so the class decides the diamond itself.

A child that inherited show() from two class parents would not know which one to use. Interfaces can still clash on default methods, but then the compiler forces the class to override the method and choose, so the ambiguity never reaches run time.

Analogies interviewers accept and reject

An analogy helps only if you map it back to Java straight away.

Example 6 · Analogies: accepted vs rejected

Text
Encapsulation  Rejected: "Like a capsule that holds medicine."  Accepted: "Like an ATM: you cannot touch the cash; you use withdraw,             and the machine enforces the limit. In Java: private             balance, public withdraw() that checks the rules."Abstraction  Rejected: "Hiding things."  Accepted: "Like driving with pedals and a steering wheel without             knowing the engine. In Java: code uses List, not ArrayList."Polymorphism  Rejected: "Poly means many, morph means forms."  Accepted: "Like a remote's power button that works for any TV brand.             In Java: p.pay() runs UPI or card code by object type."Inheritance  Rejected: "Child gets property from parents."  Accepted: "A SavingsAccount IS-A BankAccount: it reuses deposit()             and adds addInterest()."
Rule
Analogy -> immediately map it to Java names.

What this code does

  • Every accepted analogy ends with real Java: class names, a method and the rule it protects.
  • The rejected ones are not exactly wrong; they just stop before the part the interviewer is listening for.

Accepted ones show the key idea: an ATM for encapsulation (controlled operations, enforced limits), a car's pedals for abstraction (use without knowing the engine), a TV remote's power button for polymorphism (the same button works for any brand).

Rejected ones stop at the surface: "a capsule holds medicine" (no rules), "a child inherits property from parents" (Java inheritance is about types and reuse, not copying values), "poly means many, morph means forms" (a translation, not an explanation).

Next step

Check your understanding

12 quick questions