Introduce Java Encapsulation and give examples
Java encapsulation is one of the four fundamental Object-Oriented Programming (OOP) concepts, alongside inheritance, polymorphism, and abstraction. Encapsulation is the practice of bundling the data (attributes) and methods (functions) that operate on the data into a single unit, typically a class. It restricts direct access to some of the object's components, which is a means of preventing unintended interference and misuse of the methods and data.
// Class representing a Bank Account
public class BankAccount {
// Private variables (attributes)
private String accountNumber;
private double balance;
// Constructor
public BankAccount(String accountNumber, double initialBalance) {
this.accountNumber = accountNumber;
this.balance = initialBalance;
}
// Getter for accountNumber
public String getAccountNumber() {
return accountNumber;
}
// Getter for balance
public double getBalance() {
return balance;
}
// Method to deposit money
public void deposit(double amount) {
if (amount > 0) {
balance += amount;
System.out.println("Deposited: " + amount);
} else {
System.out.println("Deposit amount must be positive.");
}
}
// Method to withdraw money
public void withdraw(double amount) {
if (amount > 0 && amount <= balance) {
balance -= amount;
System.out.println("Withdrew: " + amount);
} else {
System.out.println("Invalid withdrawal amount.");
}
}
}
// Main class to test the BankAccount class
public class Main {
public static void main(String[] args) {
// Create a new bank account
BankAccount account = new BankAccount("123456789", 1000.0);
// Accessing account details using getters
System.out.println("Account Number: " + account.getAccountNumber());
System.out.println("Initial Balance: " + account.getBalance());
// Deposit money
account.deposit(500.0);
System.out.println("Balance after deposit: " + account.getBalance());
// Withdraw money
account.withdraw(200.0);
System.out.println("Balance after withdrawal: " + account.getBalance());
// Attempt to withdraw more than the balance
account.withdraw(2000.0);
}
}
accountNumber
and balance
variables are declared as private, meaning they cannot be accessed directly from outside the BankAccount
class.BankAccount
object is created.getAccountNumber()
and getBalance()
methods allow read access to the private variables.balance
or accountNumber
to prevent direct modification. Instead, we provide methods like deposit()
and withdraw()
to modify the balance safely.Main
class demonstrates how to create a BankAccount
object and interact with it using the provided methods.This encapsulation ensures that the internal state of the BankAccount
object can only be changed in controlled ways, thus maintaining the integrity of the data.