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
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
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
Final balance: 1200.06. 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
1. What is encapsulation in OOP?
2. Which access modifier restricts a member to be accessible only within the same class?
3. Which access level allows access within the same package AND by subclasses in other packages?
4. What is 'default' (package-private) access?
5. In the BankAccount example, why is `balance` declared private?
Was this page helpful?
You May Also Like
Abstraction in Java
Understand abstraction in Java through abstract classes and interfaces, and how they hide implementation details from the user.
Classes and Objects in Java
Learn how classes act as blueprints and objects as instances in Java, with syntax, examples, and exam-focused explanations.
Inheritance in Java
Understand Java inheritance using the extends keyword, the super keyword, single inheritance rules, and the Object root class.
Related Reading
Related Study Notes in Programming
Browse all study notesApache Spark Study Notes
Programming · 30 topics
ProgrammingApache Flink Study Notes
Programming · 30 topics
ProgrammingHadoop Study Notes
Programming · 30 topics
ProgrammingSnowflake Study Notes
Programming · 30 topics
ProgrammingApache Airflow Study Notes
Programming · 30 topics
Programmingdbt (Data Build Tool) Study Notes
Programming · 30 topics