Java Encapsulation
Learn Encapsulation in Java. Understand data hiding, getters, setters, and how to protect your data from unauthorized access.
Encapsulation is one of the four fundamental OOP concepts. It refers to bundling data (variables) and methods (functions) together into a single unit (class) and restricting direct access to some of an object's components.
Think of a Capsule (Medicine) 💊.
- The medicine is hidden inside the capsule.
- You can't touch the medicine directly; you swallow the capsule.
In Java, we achieve encapsulation by:
- Declaring variables as private.
- Providing public getter and setter methods to access/modify them.
Why Encapsulation? (Data Hiding)
Imagine a Bank Account.
If your balance variable is public, anyone can set it to -1000000 or 99999999.
class BankAccount {
public double balance; // BAD! Anyone can change this directly.
}With encapsulation, we make balance private and control how it changes.
class BankAccount {
private double balance; // Good! Hidden from outside.
// Getter (Read-only access)
public double getBalance() {
return balance;
}
// Setter (Write access with validation)
public void deposit(double amount) {
if (amount > 0) {
balance += amount;
} else {
System.out.println("Invalid amount!");
}
}
}Tip 💡: Encapsulation gives you control. You decide who can read (getter) and who can write (setter) your data. You can even make variables read-only by not providing a setter!
Getters and Setters
- Getter: Returns the value of a private variable.
- Setter: Sets the value of a private variable (often with validation logic).
Example: Person Class
class Person {
// Private variable
private int age;
// Getter method
public int getAge() {
return age;
}
// Setter method
public void setAge(int age) {
if (age > 0 && age < 120) {
this.age = age;
} else {
System.out.println("Please enter a valid age.");
}
}
}
public class Main {
public static void main(String[] args) {
Person p = new Person();
// p.age = -5; // Error! age is private
p.setAge(25); // Valid
System.out.println("Age: " + p.getAge());
p.setAge(-5); // Invalid, validation blocks it
}
}Benefits of Encapsulation
- Data Hiding: Users have no idea how the class stores data internally.
- Increased Flexibility: You can make variables read-only or write-only.
- Reusability: Encapsulated code is easier to reuse.
- Testing Code: It's easier to test encapsulated code.
How do you achieve data hiding in Java?
/>
Immutable Classes
An immutable class is a class whose objects cannot be modified after they are created. String and Wrapper classes (like Integer, Double) are examples of immutable classes.
To create a custom immutable class:
- Declare the class as
finalso it can't be extended. - Make all fields
privateandfinal. - Initialize fields via a constructor.
- Provide only getters (no setters).
final class ImmutablePerson {
private final String name;
private final int age;
public ImmutablePerson(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() { return name; }
public int getAge() { return age; }
}Note : Java is a statically-typed language. It means that all variables must be declared before they can be used.
Challenge
Complete this chapter to unlock the next one.
Challenge
Task:
Create a class 'User' with a private String 'password'. Add a method 'setPassword(String p)' that only updates password if length > 5.Key Takeaways
- Data Hiding: Mark fields as
private. - Accessors: Use public
gettersandsetters. - Control: Add validation logic inside setters to protect data.
Common Pitfalls
[!WARNING] Public Fields: Never make fields
publicunless they are constants (static final).Blind Setters: Don't just create a setter for every field. If a field shouldn't change (like
id), don't make a setter!
What's Next?
What if we want to define a template but force children to fill in the details? Learn Abstract Classes →
Java Access Modifiers
Master Java Access Modifiers (public, private, protected, default). Learn how to control visibility of classes, variables, and methods with real-world examples.
Java Inheritance
Complete guide to Java inheritance with examples. Learn extends keyword, super keyword, method overriding, and inheritance types in Java OOP.
