Skip to main content
Course/Module 4/Topic 3 of 3Beginner

Encapsulation & Access Modifiers

Encapsulation is the practice of hiding internal details and providing controlled access through public methods. Access modifiers (public, private, protected) control the visibility of classes, fields, and methods.

40 minBy Priygop TeamLast updated: Feb 2026

Encapsulation with Getters & Setters

Example
class BankAccount {
    // Private fields — cannot be accessed directly from outside
    private String owner;
    private double balance;
    private String accountNumber;
    
    // Constructor
    public BankAccount(String owner, double initialBalance) {
        this.owner = owner;
        this.balance = initialBalance;
        this.accountNumber = "ACC-" + (int)(Math.random() * 10000);
    }
    
    // Getter methods — read access
    public String getOwner() {
        return owner;
    }
    
    public double getBalance() {
        return balance;
    }
    
    public String getAccountNumber() {
        return accountNumber;
    }
    
    // Controlled methods with validation
    public void deposit(double amount) {
        if (amount > 0) {
            balance += amount;
            System.out.println("Deposited: $" + amount);
        } else {
            System.out.println("Invalid deposit amount!");
        }
    }
    
    public void withdraw(double amount) {
        if (amount > 0 && amount <= balance) {
            balance -= amount;
            System.out.println("Withdrew: $" + amount);
        } else {
            System.out.println("Invalid withdrawal!");
        }
    }
    
    public void printStatement() {
        System.out.println("Account: " + accountNumber);
        System.out.println("Owner: " + owner);
        System.out.println("Balance: $" + balance);
    }
}

public class EncapsulationDemo {
    public static void main(String[] args) {
        BankAccount account = new BankAccount("Alice", 1000);
        
        account.printStatement();
        account.deposit(500);
        account.withdraw(200);
        account.withdraw(5000);  // Will be rejected!
        account.deposit(-100);   // Will be rejected!
        
        System.out.println("\nFinal balance: $" + account.getBalance());
    }
}

Try It Yourself: Student Record

Try It Yourself: Student RecordJava
Java Editor
✓ ValidTab = 2 spaces
Java|60 lines|1713 chars|✓ Valid syntax
UTF-8

Quick Quiz: Encapsulation

Chat on WhatsApp
Priygop - Leading Professional Development Platform | Expert Courses & Interview Prep