Encapsulation Techniques
Understanding Encapsulation
Encapsulation is a core principle of object-oriented programming that combines data and methods into a single unit while restricting direct access to internal details.
Encapsulation Strategies
1. Getter and Setter Methods
public class User {
private String username;
private String password;
// Getter method
public String getUsername() {
return username;
}
// Setter method with validation
public void setPassword(String newPassword) {
if (isPasswordValid(newPassword)) {
this.password = newPassword;
} else {
throw new IllegalArgumentException("Invalid password");
}
}
private boolean isPasswordValid(String password) {
return password.length() >= 8 &&
password.matches(".*[A-Z].*") &&
password.matches(".*[0-9].*");
}
}
2. Read-Only Properties
public class BankAccount {
private double balance;
// Only getter, no setter
public double getBalance() {
return balance;
}
}
Encapsulation Levels
Access Modifier |
Visibility |
private |
Within class only |
protected |
Within package and subclasses |
public |
Everywhere |
default |
Within package |
Encapsulation Flow
graph TD
A[Private Data] --> B{Controlled Access}
B --> C[Getter Methods]
B --> D[Setter Methods]
C --> E[Read Operations]
D --> F[Validated Modifications]
Advanced Encapsulation Techniques
Immutable Classes
public final class ImmutablePerson {
private final String name;
private final int age;
public ImmutablePerson(String name, int age) {
this.name = name;
this.age = age;
}
// Only getters, no setters
public String getName() {
return name;
}
public int getAge() {
return age;
}
}
Benefits of Encapsulation
- Data hiding
- Improved maintainability
- Flexibility in implementation
- Enhanced security
Best Practices
- Minimize public members
- Use private fields
- Provide controlled access
- Validate data modifications
At LabEx, we recommend mastering encapsulation techniques to create robust and secure Java applications.