Encapsulation in Java
Encapsulation is a fundamental concept in object-oriented programming that allows you to bundle the data (attributes) and methods (functions) that operate on the data into a single unit or class. It also provides control over the access to the data by using access modifiers. Think of it as a capsule that contains all the necessary information and functions, but only exposes what is necessary to the outside world.
Here’s a simple example to understand encapsulation:
Example:
Imagine you are developing a banking application for a small local bank. The application needs to manage customers’ bank accounts, allowing them to deposit and withdraw money, and informing them of their current balance when they deposit or withdraw money.
import java.text.NumberFormat;
import java.util.Locale;
class BankAccount {
private double balance; // Private field for account balance
public double getBalance() { // Getter for balance
return balance;
}
private void setBalance(double balance) { // Private setter for balance
this.balance = balance;
}
// Public method to deposit money
public void deposit(double amount) {
if (amount <= 0) {
System.out.println(“Deposit amount must be positive.”);
return;
}
balance += amount;
System.out.println(“Deposited: ” + formatCurrency(amount) + “. New Balance: ” + formatCurrency(balance));
}
// Public method to withdraw money
public void withdraw(double amount) {
if (amount <= 0) {
System.out.println(“Withdrawal amount must be positive.”);
return;
}
if (amount > balance) {
System.out.println(“Insufficient funds.”);
return;
}
balance -= amount;
System.out.println(“Withdrew: ” + formatCurrency(amount) + “. New Balance: ” + formatCurrency(balance));
}
// Utility method to format currency
private String formatCurrency(double amount) {
NumberFormat currencyFormatter = NumberFormat.getCurrencyInstance(Locale.US);
return currencyFormatter.format(amount);
}
}
public class Program {
public static void main(String[] args) {
BankAccount account = new BankAccount(); // Creating a new BankAccount object
account.deposit(500); // Depositing money
account.withdraw(200); // Withdrawing money
System.out.println(“Final Balance: ” + account.getBalance()); // Outputting the final balance
}
}
Explanation:
1. BankAccount Class:
Private Field for Account Balance:
private double balance;
Getter and Private Setter for Balance:
public double getBalance() { return balance; }
private void setBalance(double balance) { this.balance = balance; }
2. Deposit Method:
Checks if the deposit amount is positive, adds the amount to balance, and prints the updated balance.
public void deposit(double amount) {
if (amount <= 0) {
System.out.println(“Deposit amount must be positive.”);
return;
}
balance += amount;
System.out.println(“Deposited: ” + formatCurrency(amount) + “. New Balance: ” + formatCurrency(balance));
}
3. Withdraw Method:
Checks if the withdrawal amount is positive and if sufficient funds are available, deducts the amount, and prints the new balance.
public void withdraw(double amount) {
if (amount <= 0) {
System.out.println(“Withdrawal amount must be positive.”);
return;
}
if (amount > balance) {
System.out.println(“Insufficient funds.”);
return;
}
balance -= amount;
System.out.println(“Withdrew: ” + formatCurrency(amount) + “. New Balance: ” + formatCurrency(balance));
}
4. Program Class with Main Method:
Creates a BankAccount object, deposits money, withdraws money, and outputs the final balance.
public static void main(String[] args) {
BankAccount account = new BankAccount();
account.deposit(500);
account.withdraw(200);
System.out.println(“Final Balance: ” + account.getBalance());
}
Tasks:
1. Basic Encapsulation:
Write a class Person with private fields for firstName and lastName. Provide public getter and setter methods to access and modify these fields. Ensure the setter methods validate that the names are not empty.
2. Read-Only Property:
Create a class Product with private fields for name, price, and stockQuantity. Provide a public getter method for name (read-only access) and getter and setter methods for price and stockQuantity.
3. Encapsulation with Methods:
Write a class BankAccount with private fields for accountNumber, balance, and ownerName. Provide public methods to deposit and withdraw money. Ensure that the withdraw method does not allow the balance to go negative.
4. Validation in Setters:
Create a class Student with private fields for studentId, name, and gpa. Implement public getter and setter methods for these fields with validation logic in the setters (e.g., studentId should be positive, name should not be null or empty, and gpa should be between 0 and 4.0).
5. Private Methods:
Write a class LibraryBook with private fields for title, author, and isCheckedOut. Provide public methods to checkOut and returnBook. Use private methods to update the status of the book.
6. Auto-Implemented Properties:
Create a class Car with auto-implemented properties for make, model, and year. Ensure that the year property cannot be set to a future year.
7. Encapsulating Collections:
Write a class Inventory that contains a private list of Item objects. Provide public methods to add and remove items, as well as to get a read-only list of items.
8. Encapsulation with Inheritance:
Create a base class Employee with private fields for name and salary. Provide public getter and setter methods for these fields. Then create a derived class Manager that adds a private field for department. Provide a public getter and setter method for department.
9. Constructor Initialization:
Write a class Order with private fields for orderId, customerName, and orderTotal. Provide a constructor to initialize these fields and getter methods to access them. Ensure the fields are initialized with valid values.
10. Computed Properties:
Create a class Rectangle with private fields for width and height. Provide public getter and setter methods for these fields. Add a read-only method getArea() that computes and returns the area of the rectangle based on width and height.
Course Video
YouTube Reference :
The training covers Java encapsulation, including its concepts, syntax, and practical applications.
Yes, it includes examples demonstrating how to bundle data and methods within a class and control access using access modifiers.
Yes, exercises involve creating classes with encapsulated fields and methods to understand their usage in various scenarios.
Yes, it’s designed for beginners with clear explanations and step-by-step examples.
A Java IDE like Eclipse, IntelliJ IDEA, or an online compiler will suffice.
Yes, it covers how encapsulation enhances data security, modularity, and code maintainability.
Yes, the training is self-paced and accessible online anytime.
Yes, it explains the distinctions and relationships between encapsulation, inheritance, and polymorphism.
It typically takes a few hours to complete, depending on your learning pace.
Yes, this Java Encapsulation training is completely free on Iqra Technology Academy’s website.