100% Free Forever
AI-Powered Learning
Industry Expert Content
Certificates & Badges
Learn At Your Own Pace
Java

Encapsulation in Java

Learn how encapsulation in Java bundles data and behavior together using private fields, access modifiers, and getters/setters.

OOP BasicsBeginner9 min readJul 7, 2026
Analogies

1. Introduction

Encapsulation is the OOP principle of bundling data (fields) and the methods that operate on that data into a single unit — a class — while restricting direct access to the internal state from outside the class. In Java, this is typically achieved by declaring fields private and exposing controlled access through public getter and setter methods.

🏏

Cricket analogy: A Batsman class bundling a private field like currentScore with a public getScore() method is like a team manager keeping a player's private fitness data locked away, only sharing sanctioned stats with the press.

Encapsulation is often described as 'data hiding' because it hides the internal implementation details of a class and only exposes what is necessary through a well-defined public interface, improving security, maintainability, and flexibility to change internal logic later without breaking external code.

🏏

Cricket analogy: Encapsulation as 'data hiding' is like a franchise not revealing a player's exact contract terms, only publishing win-loss stats publicly, so the team can renegotiate internal deals without changing what fans see.

2. Syntax

java
class ClassName {
    private dataType fieldName;

    // getter
    public dataType getFieldName() {
        return fieldName;
    }

    // setter
    public void setFieldName(dataType value) {
        // optional validation logic
        this.fieldName = value;
    }
}

3. Explanation

Java provides four access modifiers that control visibility, which are central to implementing encapsulation correctly:

🏏

Cricket analogy: Like a cricket stadium having four access tiers (VIP box, players' pavilion, media zone, general stands) each with different visibility, Java's four access modifiers (private, default, protected, public) control who can see what.

private: accessible only within the same class. default (no modifier / package-private): accessible within the same package only. protected: accessible within the same package, AND in subclasses even from different packages (via inheritance). public: accessible from anywhere in the application.

By marking fields private and providing public getter/setter methods, a class can validate incoming data (e.g., rejecting a negative age in a setter) and can later change its internal representation without affecting the code that uses the class, as long as the public method signatures stay the same.

🏏

Cricket analogy: A Player class rejecting a negative age in setAge() is like a selector committee vetoing an implausible birth year, while later changing how age is stored internally doesn't affect how commentators call getAge().

Exam trap: 'default' access (no modifier at all) is NOT the same as 'public' — default access restricts visibility to classes in the same package only, whereas public allows access from any package.

4. Example

java
public class BankAccount {
    private double balance; // hidden from direct outside access

    public BankAccount(double initialBalance) {
        if (initialBalance >= 0) {
            this.balance = initialBalance;
        }
    }

    public double getBalance() {
        return balance;
    }

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

    public void withdraw(double amount) {
        if (amount > 0 && amount <= balance) {
            balance -= amount;
        } else {
            System.out.println("Invalid withdrawal amount");
        }
    }

    public static void main(String[] args) {
        BankAccount acc = new BankAccount(1000);
        acc.deposit(500);
        acc.withdraw(300);
        System.out.println("Final balance: " + acc.getBalance());
        // acc.balance = -9999; // not allowed, balance is private
    }
}

5. Output

text
Final balance: 1200.0

6. Key Takeaways

  • Encapsulation bundles data and behavior together and hides internal state using private fields.
  • Public getters and setters provide controlled, validated access to private fields.
  • Java's four access modifiers are private, default (package-private), protected, and public.
  • Encapsulation improves security, maintainability, and flexibility to change internal implementation.
  • Default access restricts visibility to the same package, distinct from public access.

Practice what you learned

Was this page helpful?

Topics covered

#Java#JavaProgrammingStudyNotes#Programming#EncapsulationInJava#Encapsulation#Syntax#Explanation#Example#OOP#StudyNotes#SkillVeris