The four pillars
Junior Always asked 6 min
On this page
The question
Can you explain encapsulation, abstraction, inheritance and polymorphism with one example?
30-second answer
Take a Shape hierarchy. Encapsulation: Shape keeps its color private and exposes methods. Abstraction: Shape declares area() and callers use only that. Inheritance: Circle extends Shape and reuses it. Polymorphism: a loop over a List of Shape calls area() on each element, and the JVM (Java Virtual Machine) runs Circle's or Square's version depending on the object.
Understand it
The four pillars on one class diagram
Tap the partsSelect a part to see what it does.
Tap a pillar to see where it shows up in this class diagram.
View as text
A small class diagram. At the top, a client calls s.area(). Below it, the abstract class Shape has a private field color and an abstract method area(). At the bottom, Circle extends Shape, adds a private radius and overrides area().
Polymorphism: the client calls s.area() through a Shape reference, and at runtime the JVM runs Circle's area(), so a new shape works without changing the client.
Abstraction: Shape says every shape has an area() without saying how. Callers depend on that contract.
Encapsulation: color is private, so other classes must go through methods to use it. The class guards its own state.
Inheritance: Circle extends Shape. A Circle is a Shape, inherits color and fills in area(). A Java class extends exactly one parent.
A small class diagram. At the top, a client calls s.area(). Below it, the abstract class Shape has a private field color and an abstract method area(). At the bottom, Circle extends Shape, adds a private radius and overrides area().
Polymorphism: the client calls s.area() through a Shape reference, and at runtime the JVM runs Circle's area(), so a new shape works without changing the client.
Abstraction: Shape says every shape has an area() without saying how. Callers depend on that contract.
Encapsulation: color is private, so other classes must go through methods to use it. The class guards its own state.
Inheritance: Circle extends Shape. A Circle is a Shape, inherits color and fills in area(). A Java class extends exactly one parent.
Takeaway: One small hierarchy shows all four pillars: private state, a contract, a subclass, and a call that runs the right override.
Who can reach the secret field?
ExploreA private member is reachable only inside its own class: 1 of 4 places.
View as text
The class Account in package a declares a field named secret. Four places try to read it: Account itself, Audit in the same package, Savings in package b which extends Account, and Report in package b. Each place is marked Reachable or Blocked.
A private member is reachable only inside its own class: 1 of 4 places. Only Account is marked Reachable.
A package-private member, declared with no keyword, is reachable from any class in its package: 2 of 4 places. Account and Audit are Reachable.
A protected member is reachable from its package and from subclasses in other packages: 3 of 4 places. Account, Audit and Savings are Reachable; Report is Blocked.
A public member is reachable from every class: 4 of 4 places. All four are Reachable.
The class Account in package a declares a field named secret. Four places try to read it: Account itself, Audit in the same package, Savings in package b which extends Account, and Report in package b. Each place is marked Reachable or Blocked.
A private member is reachable only inside its own class: 1 of 4 places. Only Account is marked Reachable.
A package-private member, declared with no keyword, is reachable from any class in its package: 2 of 4 places. Account and Audit are Reachable.
A protected member is reachable from its package and from subclasses in other packages: 3 of 4 places. Account, Audit and Savings are Reachable; Report is Blocked.
A public member is reachable from every class: 4 of 4 places. All four are Reachable.
Takeaway: Each modifier widens the one before: private, then package-private, then protected adds subclasses elsewhere, then public reaches everyone.
In code
abstract class Shape { // abstraction: what, not how
private final String color; // encapsulation
Shape(String color) { this.color = color; }
String color() { return color; }
abstract double area();
}
class Circle extends Shape { // inheritance
private final double radius;
Circle(String color, double radius) { super(color); this.radius = radius; }
@Override double area() { return Math.PI * radius * radius; }
}
Shape s = new Circle("red", 2); // polymorphism:
double area = s.area(); // Circle's area() runs Wrong class OpenAccount { public double balance; } // anyone can write -100
class Account {
private double balance;
Right void withdraw(double amount) {
if (amount <= 0 || amount > balance) throw new IllegalArgumentException("invalid amount");
balance -= amount;
}
double balance() { return balance; }
}List<Shape> shapes = List.of(new Circle("red", 1), new Square("blue", 2));
double total = 0;
for (Shape s : shapes) total += s.area(); // each object runs its own area()Solve it
Add a payment method without touching checkout
Checkout uses a switch on a type string, "CARD" or "PAYPAL", to charge an order. Product wants crypto next month,
and every new method means editing and retesting checkout. Redesign it with the four pillars.
- Name the smell. A
switchon a type code means checkout knows every method’s details, so each new type edits code that already works. - Abstract what checkout needs. It only needs “charge this amount”. That is one interface,
PaymentMethod.pay(amount). - Encapsulate the details. A card number or a PayPal email stays private inside its own class; checkout never sees it.
- Let polymorphism pick. Checkout calls
method.pay(total)and the object’s ownpayruns. Crypto is one new class. - Check the trade-off. No base class is needed: an interface is enough until several methods share state or steps.
interface PaymentMethod { Receipt pay(Money amount); }
class Card implements PaymentMethod {
private final String number;
Card(String number) { this.number = number; }
public Receipt pay(Money amount) { return Receipt.paid(amount, "card " + number.substring(number.length() - 4)); }
}
class Crypto implements PaymentMethod { // new method, checkout unchanged
private final String wallet;
Crypto(String wallet) { this.wallet = wallet; }
public Receipt pay(Money amount) { return Receipt.paid(amount, "wallet " + wallet); }
}
class Checkout {
Receipt complete(Order order, PaymentMethod method) { return method.pay(order.total()); }
}How to answer
- Encapsulation hides state behind methods, so the class controls every change to it.
- Abstraction exposes what an object does and hides how it does it.
- Inheritance lets a subclass reuse and specialize a parent: a Circle is a Shape.
- Polymorphism runs the override of the actual object behind a parent-type reference.
- Use one running example for all four; it shows how they work together.
Common mistakes
- Defining encapsulation as "getters and setters"; a setter for every field exposes state almost as much as a public field.
- Treating abstraction as a synonym for abstract classes; interfaces and well-named methods abstract too.
Follow-up questions
What is the difference between encapsulation and abstraction?
Abstraction is the outside view: a type exposes what it does, like area(), and hides how. Encapsulation is the inside: the class hides its state and controls access to it. Abstraction designs the contract; encapsulation protects the implementation behind it.
- Abstraction: what callers see and depend on.
- Encapsulation: how the class protects its own data.
- Both shrink what callers need to know.
See it in the infographic: The four pillars on one class diagram
Why make fields private instead of public?
A private field changes only through the class's own methods, so the class can validate every change, keep its rules true and later change how it stores the data without breaking callers. A public field lets any class in the program break it.
- Methods can validate input and keep the object valid.
- The internal representation can change without breaking callers.
- When a value is wrong, there are fewer places to look.
See it in the infographic: Who can reach the secret field? See it in the infographic: The four pillars on one class diagram
What is the difference between private, package-private, protected and public?
Each one widens the one before. private: only the declaring class. Package-private, the default with no keyword: any class in the same package. protected: the same package plus subclasses in other packages. public: every class.
- No keyword means package-private, not public.
- protected also opens the member to the whole package, not only to subclasses.
- Start with the narrowest access that works.
How does polymorphism show up in a loop over a list of shapes?
The loop calls area() through a Shape reference. Each element is really a Circle or a Square, and the JVM runs that class's area(). Adding a Triangle means writing a new class, not changing the loop.
- The reference type is Shape; the object decides which method runs.
- New shapes extend the program without editing the loop.
List<Shape> shapes = List.of(new Circle(1), new Square(2));
for (Shape s : shapes) {
System.out.println(s.area()); // Circle's, then Square's
} See it in the infographic: The four pillars on one class diagram
When is inheritance the wrong way to reuse code?
When the subclass is not truly a kind of the parent, or only wants some of its methods. Extending a class to borrow code ties the subclass to the parent's internals, so a change in the parent can break it. Holding the other object as a field, composition, reuses the code without that tie.
- Inherit for an is-a relationship, not for code reuse alone.
- A subclass depends on how its parent is implemented.
- Prefer composition when only the behavior is needed.
See it in the infographic: The four pillars on one class diagram
Does Java support multiple inheritance?
Of type, yes: a class can implement many interfaces. Of implementation, no: a class extends exactly one class, which avoids two parents each bringing their own fields and constructors.
Are getters and setters encapsulation?
Only partly. A setter for every field still lets callers put the object in any state. Real encapsulation exposes operations such as withdraw(amount) that keep the object valid.
Can a subclass in another package use a protected field?
Yes, as its own inherited member. A class in another package that is not a subclass gets a compile error, so protected is wider than package-private but narrower than public.
Check yourself
Show answers
- Every class: Incorrect. No keyword means package-private, not public.
- Classes in the same package: Correct. Package-private is the default and reaches only the declaring package.
- Only subclasses: Incorrect. Subclasses in other packages need protected; package-private does not reach them.
Show answers
- Subclasses of Account: Correct. protected reaches subclasses in any package, through their inherited member.
- Any class: Incorrect. A non-subclass in another package gets a compile error.
- No class: Incorrect. protected is wider than package-private; it adds subclasses everywhere.
Show answers
- Encapsulation: Incorrect. Hiding fields does not decide which area() runs.
- Inheritance: Incorrect. Inheritance gives the shared Shape type; picking the override at runtime is polymorphism.
- Polymorphism: Correct. The JVM runs each object's own area() behind the Shape reference.