Encapsulation is a fundamental concept in object-oriented programming (OOP) that plays a crucial role in safeguarding data in scalable way. It's like special box where you keep precious items and deciding who can access them and under what conditions.
What is Encapsulation?
At its core, encapsulation involves bundling data (variables) and methods (functions) in a class. By controlling access to this data, encapsulation helps in maintaining a safe environment for the data.
Key Aspects of Encapsulation:
Private Variables: Like having a private toy box, private variables are not accessible outside the class. This is for having a safe for your valuables.
Public Methods: These are the controlled pathways through which external code can interact with the private data, similar to having a secure procedure to access a safe.
Implementing Encapsulation: Java Examples
1. PiggyBank Example
Consider a PiggyBank
class designed to manage money. Here's how encapsulation is applied:
public class PiggyBank {
private int totalAmount; // Private field, like money inside a piggy bank
// Constructor
public PiggyBank() {
this.totalAmount = 0;
}
// Method to add money
public void addMoney(int amount) {
if (amount > 0) {
totalAmount += amount;
System.out.println(amount + " added to the piggy bank!");
}
}
// Method to check balance
public int checkBalance() {
return totalAmount;
}
}
In this example, totalAmount
is private, ensuring it cannot be accessed or modified directly outside the class, enforcing the rules for piggy bank.
2. Variations in Access Modifiers
Protected Access Modifier: Allows access within the same class, subclasses, and the same package.
Default (Package-Private) Access Modifier: Allows access only within the same package.
3. Read-Only and Write-Only Properties
Read-Only: Public getter methods without setters, allowing external entities to read but not modify the property.
Write-Only: Public setter methods without getters, allowing modifications but not reading of the property.