What are the four pillars of OOP, and how does Java support each?
8 minbeginneroopbasics
Quick Answer
Encapsulation (private fields + public accessors), Abstraction (abstract classes/interfaces hiding implementation), Inheritance (extends/implements for reuse and 'is-a' relationships), and Polymorphism (overriding/overloading letting the same call behave differently by runtime type).
Detailed Answer
- Encapsulation: bundling state and behavior together and restricting direct access to internals via access modifiers (
privatefields,publicgetters/setters or methods that validate input).
class Account {
private double balance;
public void deposit(double amt) {
if (amt <= 0) throw new IllegalArgumentException();
balance += amt;
}
}
- Abstraction: exposing what an object does while hiding how, via
abstractclasses and interfaces that define a contract without full implementation. - Inheritance: a subclass (
extends) reuses and specializes a superclass's fields/methods, modeling an "is-a" relationship. Java supports single inheritance of classes but multiple inheritance of interfaces. - Polymorphism: the same method call behaves differently depending on the actual runtime type (overriding, resolved dynamically via virtual dispatch) or on argument types at compile time (overloading).
Shape s = new Circle(5);
s.area(); // calls Circle.area() at runtime, even though s is typed as Shape
Java's design (single class inheritance + interfaces, mandatory access modifiers, and virtual-by-default instance methods) makes all four pillars first-class, idiomatic parts of the language rather than conventions layered on top.