Among Java's four core OOP principles, encapsulation bundles data (attributes) and methods (functions) into a single unit called a class, alongside inheritance, polymorphism, and abstraction.
Scenario:
Suppose we are building a simple banking system where we have a BankAccount class. Each bank account has an account number, account holder name, account type and a balance. We want to encapsulate these attributes and provide methods to interact with them safely.
Create the BankAccount class:
public class BankAccount {
// Attributes (encapsulated)
private long accountNumber;
private String accountHolderName;
private String accountType;
private double balance;
// Constructor
public BankAccount(long accountNumber,String accountHolderName,
String accountType,double balance) {
this.accountNumber = accountNumber;
this.accountHolderName=accountHolderName;
this.accountType=accountType
this.balance = balance;
}
// Getter for accountNumber
public double getAccountNumber() {
return accountNumber;
}
// Getter for balance
public double getBalance() {
return balance;
}
// Setter for balance
public void setBalance(double balance) {
this.balance = balance;
}
// same way other Getter/setter for remaining properties of BankAccount
//Override toString method of Object to print BankAccount all data together
@Override
public String toString(){
return this.getAccountNumber()+", "+this.getAccountHolderName()+", "+this.getAccountType()+", "+this.getBalance();
}
}
Encapsulate the attributes:
An accountNumber, accountHolderName, accountType and balance attributes are declared as private. It means they cannot be accessed directly from outside the class.
Provide getter and setter methods:
Getter methods like getBalance() and getAccountNumber() allow external classes to retrieve the values of the encapsulated attributes.
Setter method setBalance() allows external classes to modify the value of the balance attribute. It means we should not provide accountNumber for setter otherwise it can also be changed which is not possible in real life scenarios.
Usage the above defined BankAccount example:
public class Main {
public static void main(String[] args) {
// Create a new BankAccount object
BankAccount account = new BankAccount(1234567890,"Komali","Saving",12780);
//Print all data together
System.out.println(account);
// add more amount using setter to set new balance
account.setBalance(account.getBalance()+1000.0);
// Use getter to retrieve balance
double balance = account.getBalance();
System.out.println("New Balance: $" + balance);
// Try to directly access the attribute (will cause compilation error)
// System.out.println(account.balance); // Compilation error: balance has private access in BankAccount
}
}
Results:
The output will be:
1234567890, Komali, Saving, 12780
New Balance: $13780.0
Conclusion:
Through encapsulation, we've hidden the internal state of the BankAccount object (accountNumber, accountHolderName, accountType and balance) from direct access.
We provided controlled access to these attributes through getter and setter methods but not provided setter for accountNumber. It means once any BankAccount created all information can be changed but not accountNumber which uniquely presenting in entire bank accountNumber.
This promotes data security and helps maintain the integrity of the object's state.
Try Now Following Assignments:
Use Case 1:
Create an Employee class with properties such as name, id, salary, and department. Implement setter and getter methods for each property. Additionally, include a method to calculate and return the yearly salary of the employee.
Use Case 2:
Design a Student class with attributes like name, rollNumber, marks (in an array for different subjects), and grade. Implement methods to set and get these attributes, along with a method to calculate and return the average marks of the student.
Use Case 3:
Define a Book class with attributes such as title, author, isbn, price, and numPages. Provide methods to access and modify these attributes. Also, include a method to display the details of the book.
Use Case 4:
Create a Car class with properties like make, model, year, mileage, and price. Implement appropriate methods to set and get these properties. Additionally, include a method to calculate and return the depreciated value of the car based on its mileage and year of manufacture.