</>

Technology

Core Java

Difficulty

Beginner

Interview Question

What are the 4 pillars of Object-Oriented Programming (OOP) in Java?

Answer

4 Pillars of OOP in Java

1. Encapsulation — "Data Hiding"

Wrapping data (fields) and methods into a single unit (class), and restricting direct access using access modifiers.

Java
public class BankAccount {
    private double balance;  // hidden — cannot access directly

    public double getBalance() { return balance; }  // controlled access

    public void deposit(double amount) {
        if (amount > 0) balance += amount;  // validation before changing
    }
}

// Usage
BankAccount acc = new BankAccount();
acc.deposit(1000);
System.out.println(acc.getBalance()); // 1000.0
// acc.balance = -5000; // ❌ compile error — private

Benefits: Data validation, security, flexibility to change implementation.

2. Inheritance — "Code Reuse"

A child class acquires properties and behavior of a parent class using extends.

Java
public class Animal {
    public void eat() {
        System.out.println("Animal eats");
    }
}

public class Dog extends Animal {
    public void bark() {
        System.out.println("Dog barks");
    }
}

Dog dog = new Dog();
dog.eat();   // inherited from Animal
dog.bark();  // own method

Types in Java: Single, Multilevel, Hierarchical (Multiple inheritance via class is NOT supported — use interfaces).

3. Polymorphism — "Many Forms"

Same method name behaves differently based on context.

Compile-time (Method Overloading):

Java
public class Calculator {
    public int add(int a, int b)       { return a + b; }
    public double add(double a, double b) { return a + b; }
    public int add(int a, int b, int c) { return a + b + c; }
}

Runtime (Method Overriding):

Java
Animal animal = new Dog();
animal.eat(); // calls Dog's version at runtime

4. Abstraction — "Hide Complexity"

Show only what is necessary; hide implementation details.

Java
// Abstract class
abstract class Shape {
    abstract double area();  // no body — must be implemented
    public void display() {
        System.out.println("Area: " + area());
    }
}

class Circle extends Shape {
    double radius;
    Circle(double r) { radius = r; }

    @Override
    double area() { return Math.PI * radius * radius; }
}

Also achieved via Interfaces (100% abstraction).

Quick Summary

PillarKeywordPurpose
Encapsulationprivate + getters/settersData protection
InheritanceextendsCode reuse
PolymorphismOverloading / OverridingFlexibility
Abstractionabstract / interfaceHide complexity

Follow AutomateQA

Related Topics