Java Encapsulation
Protecting data and controlling access in Java classes
🔒 What is Encapsulation?
Encapsulation is hiding internal data and providing controlled access through methods. It protects class data from unauthorized access and maintains data integrity in object-oriented programming.
// Simple encapsulation example
public class Student {
private String name; // Hidden data
public void setName(String name) { // Controlled access
this.name = name;
}
public String getName() {
return name;
}
}
Output:
Data is protected and accessed through methods
Key Encapsulation Concepts
Private Fields
Hide data from outside access
private int age;
Getter Methods
Provide read access to private data
public int getAge() {
return age;
}
Setter Methods
Provide controlled write access
public void setAge(int age) {
if(age > 0) this.age = age;
}
Data Validation
Ensure data integrity
if(email.contains("@")) {
this.email = email;
}
🔹 Complete Encapsulation Example
Here's a fully encapsulated class with validation:
public class BankAccount {
private String accountNumber;
private double balance;
private String ownerName;
// Constructor
public BankAccount(String accountNumber, String ownerName) {
this.accountNumber = accountNumber;
this.ownerName = ownerName;
this.balance = 0.0;
}
// Getter methods
public String getAccountNumber() {
return accountNumber;
}
public double getBalance() {
return balance;
}
public String getOwnerName() {
return ownerName;
}
// Controlled methods for balance
public void deposit(double amount) {
if(amount > 0) {
balance += amount;
System.out.println("Deposited: $" + amount);
}
}
public void withdraw(double amount) {
if(amount > 0 && amount <= balance) {
balance -= amount;
System.out.println("Withdrawn: $" + amount);
} else {
System.out.println("Invalid withdrawal amount");
}
}
}
Usage:
BankAccount account = new BankAccount("12345", "John");
account.deposit(1000.0);
account.withdraw(500.0);
System.out.println("Balance: $" + account.getBalance());
🔹 Benefits of Encapsulation
- Data Security: Private fields prevent unauthorized access
- Data Validation: Setters can validate input before storing
- Flexibility: Internal implementation can change without affecting users
- Maintainability: Easier to debug and modify code
public class Person {
private int age;
public void setAge(int age) {
// Validation ensures data integrity
if(age >= 0 && age <= 150) {
this.age = age;
} else {
System.out.println("Invalid age!");
}
}
public int getAge() {
return age;
}
}