OOP

Object-Oriented Programming

Learn the four pillars of OOP in Java: encapsulation, inheritance, polymorphism, and abstraction.

Classes and Objects

A class is a blueprint. An object is an instance of that blueprint.

Encapsulation

Hide internal state and require access through methods (getters/setters). Use private fields.

Inheritance

A class can inherit fields and methods from another class using extends.

Polymorphism

Objects of different classes can be treated as objects of a common superclass.

Abstraction

Abstract classes and interfaces define contracts without full implementation.

Example

java
// Class with encapsulation
public class BankAccount {
    private String owner;
    private double balance;

    public BankAccount(String owner, double initialBalance) {
        this.owner = owner;
        this.balance = initialBalance;
    }

    public double getBalance() { return balance; }

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

    public boolean withdraw(double amount) {
        if (amount <= balance) {
            balance -= amount;
            return true;
        }
        return false;
    }
}

// Inheritance
public class SavingsAccount extends BankAccount {
    private double interestRate;

    public SavingsAccount(String owner, double balance, double rate) {
        super(owner, balance);
        this.interestRate = rate;
    }

    public void applyInterest() {
        deposit(getBalance() * interestRate);
    }
}

// Abstract class
abstract class Shape {
    abstract double area();

    void printArea() {
        System.out.println("Area: " + area());
    }
}

// Polymorphism
class Circle extends Shape {
    double radius;
    Circle(double r) { radius = r; }
    double area() { return Math.PI * radius * radius; }
}

class Main {
    public static void main(String[] args) {
        Shape s = new Circle(5.0);
        s.printArea(); // Area: 78.53...
    }
}
Try it yourself — JAVA