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.
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.
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); // 40Every 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#
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.
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.
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.
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.@Overrideasks 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.
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)#
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)#
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.
| Overloading | Overriding | |
|---|---|---|
| Where | Same class | Parent and child class |
| Signature | Different parameters | Same name and parameters |
| Decided at | Compile time | Runtime |
| Purpose | Convenience for callers | Change 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#
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#
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; }
}| Interface | Abstract class | |
|---|---|---|
| Can hold state (fields) | Only constants | Yes |
| Constructors | No | Yes |
| Multiple per class | A class can implement many | A class can extend only one |
| Use when | Defining 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
extendsare 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.