Skip to main content
1:1 mock interviews with Sumit, scored on a real hiring rubric.Book a slot →

OOP in Java: The Four Pillars Explained with Examples

Learn object-oriented programming in Java: classes and objects, then encapsulation, inheritance, polymorphism and abstraction, with clear code examples and the mistakes to avoid.

Sumit KumarUpdated Oct 11, 20265 min readJava
OOP in Java: The Four Pillars Explained with Examples

Object-oriented programming (OOP) organises code around objects: bundles of data and the behaviour that works on that data. Java was designed around OOP, so understanding its four pillars is the foundation for everything else you write in the language.

Classes and objects#

A class is a blueprint. An object is a real thing built from that blueprint, with its own values.

Java
public class Car {
    String brand;
    int speed;

    void accelerate(int amount) {
        speed += amount;
    }
}

Car myCar = new Car();      // an object (instance) of Car
myCar.brand = "Tata";
myCar.accelerate(40);
System.out.println(myCar.speed); // 40

Every object has state (its fields, like brand and speed) and behaviour (its methods, like accelerate). Two Car objects share the same methods but keep separate state.

The four pillars at a glance#

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

1. Encapsulation: protect your data#

Encapsulation means keeping fields private and only allowing changes through methods. The class stays in control of its own state, so it can never end up invalid.

Java
public class BankAccount {
    private double balance;   // hidden from outside code

    public double getBalance() {
        return balance;
    }

    public void deposit(double amount) {
        if (amount <= 0) {
            throw new IllegalArgumentException("Deposit must be positive");
        }
        balance += amount;
    }

    public void withdraw(double amount) {
        if (amount > balance) {
            throw new IllegalStateException("Insufficient funds");
        }
        balance -= amount;
    }
}

Nobody can write account.balance = -5000. Every change goes through deposit or withdraw, which enforce the rules in one place.

Tip

Don't generate a setter for every field by reflex. Only expose the operations the rest of your code genuinely needs. A deposit() method says more than setBalance().

2. Inheritance: reuse with extends#

Inheritance lets a class reuse the fields and methods of another class. The child class gets everything from the parent and can add or change behaviour. It models an is-a relationship: a Dog is an Animal.

Java
public class Animal {
    protected String name;

    public Animal(String name) {
        this.name = name;
    }

    public void eat() {
        System.out.println(name + " is eating");
    }

    public String sound() {
        return "...";
    }
}

public class Dog extends Animal {
    public Dog(String name) {
        super(name);          // call the parent constructor
    }

    @Override
    public String sound() {   // replace the parent's behaviour
        return "Woof";
    }

    public void fetch() {     // add new behaviour
        System.out.println(name + " fetches the ball");
    }
}
  • super(name) calls the parent constructor.
  • @Override asks the compiler to check that you really are overriding a parent method. Always use it: a typo becomes a compile error instead of a silent bug.
  • Java supports single inheritance for classes: a class can extend only one parent.
Prefer composition

Inheritance couples the child tightly to the parent. If the relationship is has-a (a Car has an Engine), use a field instead of extends. "Favour composition over inheritance" is one of the most useful design rules in Java.

3. Polymorphism: one call, many forms#

Polymorphism means the same method call can do different things depending on the actual object. Java has two kinds.

Runtime polymorphism (overriding)#

Java
public class Cat extends Animal {
    public Cat(String name) { super(name); }

    @Override
    public String sound() { return "Meow"; }
}

List<Animal> animals = List.of(new Dog("Rex"), new Cat("Milo"));
for (Animal a : animals) {
    System.out.println(a.sound());   // Woof, then Meow
}

The variable type is Animal, but Java calls the method of the real object at runtime. This is called dynamic dispatch. It lets you write code against a general type and add new subtypes later without changing that code.

Compile-time polymorphism (overloading)#

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

Overloaded methods share a name but have different parameter lists. The compiler picks the right one from the arguments.

OverloadingOverriding
WhereSame classParent and child class
SignatureDifferent parametersSame name and parameters
Decided atCompile timeRuntime
PurposeConvenience for callersChange behaviour in subtypes

4. Abstraction: show what, hide how#

Abstraction means exposing only what callers need and hiding the details. Java provides two tools for it.

Interfaces#

Java
public interface PaymentMethod {
    void pay(double amount);
}

public class UpiPayment implements PaymentMethod {
    public void pay(double amount) {
        System.out.println("Paid ₹" + amount + " via UPI");
    }
}

public class CardPayment implements PaymentMethod {
    public void pay(double amount) {
        System.out.println("Paid ₹" + amount + " by card");
    }
}

void checkout(PaymentMethod method, double total) {
    method.pay(total);   // doesn't care how payment works
}

The checkout method depends only on the contract. You can add a WalletPayment tomorrow without touching it.

Abstract classes#

Java
public abstract class Shape {
    public abstract double area();          // no body: subclasses must implement

    public void describe() {                // shared, concrete behaviour
        System.out.println("Area: " + area());
    }
}

public class Circle extends Shape {
    private final double radius;
    public Circle(double radius) { this.radius = radius; }
    public double area() { return Math.PI * radius * radius; }
}
InterfaceAbstract class
Can hold state (fields)Only constantsYes
ConstructorsNoYes
Multiple per classA class can implement manyA class can extend only one
Use whenDefining a capability (Comparable, Runnable)Sharing code between closely related classes

Since Java 8, interfaces can also have default and static methods, which narrows the gap. A good default: start with an interface, and introduce an abstract class only when several implementations need to share real code or state.

How the pillars work together#

In real code the pillars support each other. BankAccount encapsulates its balance. SavingsAccount and CurrentAccount inherit from it. A method that takes any BankAccount works polymorphically with both. And an InterestPolicy interface abstracts how interest is calculated, so you can change the rule without touching the accounts.

Common mistakes#

  • Public fields everywhere. They break encapsulation and let any code put objects in an invalid state.
  • Deep inheritance chains. Five levels of extends are hard to follow and fragile. Keep hierarchies shallow.
  • Forgetting @Override. A misspelled method name silently creates a new method instead of overriding.
  • Using inheritance just to reuse code. If it isn't a true is-a relationship, use composition.

Next, see how these ideas power Java's standard library in our Java Collections Framework guide, where List, Set and Map are interfaces with several implementations.

Key takeaways#

  • A class is a blueprint; an object is an instance with its own state.
  • Encapsulation keeps fields private and changes them only through validated methods.
  • Inheritance reuses code for is-a relationships; prefer composition for has-a.
  • Polymorphism lets one call behave differently per object (overriding) or per argument list (overloading).
  • Abstraction exposes contracts through interfaces and abstract classes and hides the details.