What are the four pillars of object-oriented programming in Java?
Encapsulation hides data behind methods, abstraction exposes only what matters, inheritance reuses a parent class, and polymorphism lets one call behave differently depending on the actual object.
Explain it simply
Think of an ATM. You press buttons and get cash (abstraction). The cash drawer and the bank servers are locked away from you (encapsulation). A savings ATM and a currency-exchange ATM are both "ATMs" and share the same card slot (inheritance). Press "withdraw" and each type does its own thing (polymorphism).
Example
abstract class Account {
private double balance; // encapsulation: private data
void deposit(double amt) { if (amt > 0) balance += amt; }
double getBalance() { return balance; }
abstract double monthlyCharge(); // abstraction: what, not how
}
class Savings extends Account { // inheritance
double monthlyCharge() { return 0; }
}
class Current extends Account {
double monthlyCharge() { return 150; } // same call, different behaviour
}
// Account a = new Current(); a.monthlyCharge() returns 150.0What to say in the interview
"Encapsulation keeps fields private and controls access through methods. Abstraction exposes a simple contract through abstract classes or interfaces. Inheritance lets a subclass reuse and extend a parent. Polymorphism means a parent reference can hold a child object and the overridden method that runs is decided at runtime."
Common mistakes
- Saying encapsulation just means "make fields private". The point is controlling how state changes, such as rejecting a negative deposit.
- Confusing abstraction (hiding complexity of design) with encapsulation (hiding data).