Hiprup

What are the four pillars of Object-Oriented Programming in Java?

The four pillars of OOP in Java are encapsulation, inheritance, polymorphism, and abstraction.

  • Encapsulation — bundle data and methods inside a class; expose only via getters/setters with private fields.

  • Inheritance — a child class reuses behavior from a parent via extends; promotes code reuse.

  • Polymorphism — one interface, many forms. Overloading (compile-time) and overriding (runtime) let the same method name behave differently.

  • Abstraction — hide implementation details; expose only the contract via abstract classes and interfaces.

// Encapsulation
public class BankAccount {
    private double balance;
    public void deposit(double amount) {
        if (amount > 0) balance += amount;
    }
    public double getBalance() { return balance; }
}

// Inheritance + Polymorphism
public abstract class Shape {
    abstract double area(); // Abstraction
}

public class Circle extends Shape { // Inheritance
    private double radius;
    public Circle(double r) { this.radius = r; }
    @Override
    double area() { return Math.PI * radius * radius; } // Polymorphism
}

public class Rectangle extends Shape {
    private double width, height;
    public Rectangle(double w, double h) { width = w; height = h; }
    @Override
    double area() { return width * height; }
}

// Runtime polymorphism
Shape s = new Circle(5); // Reference type: Shape, Object type: Circle
System.out.println(s.area()); // Calls Circle.area() — dynamic dispatch

BankAccount encapsulates balance with private access and validates deposits. Shape is abstract — it cannot be instantiated and forces subclasses to implement area().

Circle and Rectangle inherit from Shape and provide their own area() implementations. The variable s is typed as Shape but holds a Circle — calling area() dispatches to Circle's implementation at runtime.

Give a concrete example for each pillar, not just definitions. The Shape/Circle/Rectangle hierarchy demonstrates three pillars at once.

Mention that Java supports single class inheritance but multiple interface inheritance.

What are the four pillars of Object-Oriented Programming in Java? | Hiprup