Java for Everyone...Encapsulation.
Consider a real-life example of your bank account. Your account balance is private—you wouldn’t want anyone to directly change it. However, you’d welcome someone depositing money into your account. This demonstrates the concept of data privacy.
Here, your account balance represents private data, while the deposit method is a public method that allows controlled access to modify the balance. Similarly, the withdraw method, also public, provides another controlled way to interact with your balance.
Now, Encapsulation by definition - Encapsulation describes the ability of an object to hide its data and methods from the rest of the world and is one of the fundamental principles of object-oriented programming.
It also enables you to restrict access only to those features of an object that are declared public. All other fields and methods are private and can be used for internal object processing.
Take this example...
package Encapsualtions;
public class BankAccount {
// balance should be private, should not accessible by script or APIs.
private double balance;
// Now initialize balance using constructor
public BankAccount(double initialBalance) {
this.balance = initialBalance;
}
// Public method to check balance
public double getBalance() {
return balance;
}
public void Deposit(double amount) {
if (amount > 0) {
balance = balance + amount;
} else {
System.out.println("You don't have sufficient amount");
}
}
public void Withdraw(double amount) {
if (amount > 0 && amount <= amount) {
balance = balance - amount;
} else {
System.out.println("Enter another amount for your withdrawal");
}
}
public static void main(String[] args) {
BankAccount bankaccount = new BankAccount(1000);
bankaccount.Deposit(1);
bankaccount.Withdraw(9);
System.out.println("Your Available amount is ?:" + bankaccount.getBalance());
}
}
//output
Your Available amount is ?:992.0
Why Constructor?
If there were no constructor, you would need to explicitly set the balance using a separate method, like
BankAccount bankaccount = new BankAccount();
bankaccount.Deposit(5000); // Set initial balance
领英推荐
?The constructor simplifies and enforces proper initialization of the BankAccount object, ensuring it starts with a valid state (balance initialized). This is a key principle of object-oriented programming and encapsulation.
Why 'this'?
In the constructor, this is used to access the instance variable of the object being constructed, using 'this' explicitly specifies that you're assigning the value to the instance variable ie- initialBalance.
Take another Example
package Encapsualtions;
public class BankAccount1 {
// Private data members
private String AcntNumber;
private String AcntHolder;
private double balance;
// Constructor to initialize data members
public BankAccount1(String accountNumber, String accountHolderName, double initialBalance) {
this.AcntNumber = accountNumber;
this.AcntHolder = accountHolderName;
this.balance = initialBalance;
}
// Public getter and setter methods to access private data
public String getAccountNumber() {
return AcntNumber;
}
// Get and set account holder name
public String getAccountHolderName() {
return AcntHolder;
}
public void setAccountHolderName(String accountHolderName) {
this.AcntHolder = accountHolderName;
}
// Get balance (read-only, no direct setter)
public double getBalance() {
return balance;
}
// Deposit method (modifies private balance)
public void deposit(double amount) {
if (amount > 0) {
balance += amount;
System.out.println("\nDeposited amount ?" + amount);
} else {
System.out.println("Transaction failed!");
}
}
// Withdraw method (modifies private balance)
public void withdraw(double amount) {
if (amount > 0 && amount <= balance) {
balance -= amount;
System.out.println("Successfully withdrawn:?" + amount);
} else {
System.out.println("\nInsufficient funds!");
}
}
public static void main(String[] args) {
// Create a new bank account
BankAccount1 account = new BankAccount1("00000001", "Arjun Kr Mandal", 999.00);
// Access account details using public methods
System.out.println("Account Holder: " + account.getAccountHolderName());
System.out.println("Account Number: " + account.getAccountNumber());
System.out.println("Current Balance: ?" + account.getBalance());
// Perform deposit and withdrawal
account.deposit(99.00);
System.out.println("Updated Balance: ?" + account.getBalance());
account.withdraw(9.00);
System.out.println("Updated Balance: ?" + account.getBalance());
// Attempt invalid transactions
account.withdraw(9999.00); // Insufficient funds
}
}
//output
Account Holder: Arjun Kr Mandal
Account Number: 00000001
Current Balance: ?999.0
Deposited amount ?99.0
Updated Balance: ?1098.0
Successfully withdrawn:?9.0
Updated Balance: ?1089.0
Insufficient funds!
Encapsulation in Java is typically achieved by declaring instance variables as private and providing controlled access to them through methods, such as getters and setters, for reading and modifying their values.
Remember, getter and setter methods are key to the encapsulation principle in object-oriented programming. They protect an object's internal state (e.g., the balance field) by preventing direct access from external code. Instead, interactions are managed through controlled methods.
In summary, the key benefits of encapsulation include:
Keep following https://www.dhirubhai.net/in/arjunkrm-testarchitect/ for such interesting topics.