An example of encapsulation in Java is using private fields within a class and providing public getter and setter methods to control access to those fields. This ensures that the internal representation of an object is hidden from the outside world, allowing controlled access and modification of the data. Encapsulation helps maintain data integrity and simplifies code maintenance.
public class BankAccount {
private double balance; // Private field to encapsulate the balance
// Constructor
public BankAccount(double initialBalance) {
this.balance = initialBalance;
}
// Public getter method to access the balance
public double getBalance() {
return balance;
}
// Public setter method to modify the balance
public void deposit(double amount) {
if (amount > 0) { // Validating input to maintain data integrity
balance += amount;
} else {
System.out.println("Deposit amount must be positive.");
}
}
public void withdraw(double amount) {
if (amount > 0 && amount <= balance) {
balance -= amount;
} else {
System.out.println("Insufficient funds or invalid amount.");
}
}
}
Usage:
BankAccount account = new BankAccount(1000.0);
account.deposit(500.0);
account.withdraw(300.0);
System.out.println("Balance: " + account.getBalance()); // Accesses the balance'