Here are a few program examples that demonstrate the use of encapsulation through getter and setter
methods, along with detailed explanations.
### Example 1: Employee Details
This example shows how to encapsulate an employee's information, such as name and salary, and
access it via getter and setter methods.
Code:
package encapsulation;
class Employee {
private String name;
private double salary;
// Getter for name
public String getName() {
return name;
}
// Setter for name
public void setName(String name) {
this.name = name;
}
// Getter for salary
public double getSalary() {
return salary;
}
// Setter for salary
public void setSalary(double salary) {
if (salary > 0) { // Validation to ensure salary is positive
this.salary = salary;
} else {
System.out.println("Salary must be greater than zero.");
}
}
}
public class TestEmployee {
public static void main(String[] args) {
Employee emp = new Employee();
// Setting values through setter methods
emp.setName("John Doe");
emp.setSalary(50000);
// Retrieving values through getter methods
System.out.println("Employee Name: " + emp.getName());
System.out.println("Employee Salary: $" + emp.getSalary());
}
}
Explanation:
- **Encapsulation** is achieved by making the `name` and `salary` fields private.
- The `setName()` and `setSalary()` methods allow controlled access to modify the private fields.
- The `getName()` and `getSalary()` methods provide read access to these fields.
- Additional logic is included to ensure the salary is positive.
Example 2: Student Marks
In this example, we encapsulate a student's details (name and marks) and ensure that the marks are
within a valid range.
Code:
package encapsulation;
class Student {
private String name;
private int marks;
// Getter for name
public String getName() {
return name;
}
// Setter for name
public void setName(String name) {
this.name = name;
}
// Getter for marks
public int getMarks() {
return marks;
}
// Setter for marks with validation
public void setMarks(int marks) {
if (marks >= 0 && marks <= 100) { // Validation to ensure marks are between 0 and 100
this.marks = marks;
} else {
System.out.println("Invalid marks. Must be between 0 and 100.");
}
}
}
public class TestStudent {
public static void main(String[] args) {
Student student = new Student();
// Setting values
student.setName("Alice");
student.setMarks(85);
// Getting values
System.out.println("Student Name: " + student.getName());
System.out.println("Student Marks: " + student.getMarks());
// Trying to set invalid marks
student.setMarks(120); // This will trigger the validation message
}
}
Explanation:
- **Encapsulation** is used to protect the `name` and `marks` fields.
- The `setMarks()` method has validation to ensure that the marks fall within the range of 0 to 100.
- This example shows how encapsulation allows for data validation and restricted access to class
members.
Example 3: Bank Account
This example encapsulates a bank account's details and provides controlled access for depositing and
withdrawing money.
Code:
package encapsulation;
class BankAccount {
private String accountNumber;
private double balance;
// Getter for account number
public String getAccountNumber() {
return accountNumber;
}
// Setter for account number
public void setAccountNumber(String accountNumber) {
this.accountNumber = accountNumber;
}
// Getter for balance
public double getBalance() {
return balance;
}
// Method to deposit money
public void deposit(double amount) {
if (amount > 0) {
balance += 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;
} else {
System.out.println("Invalid withdrawal amount or insufficient balance.");
}
}
}
public class TestBankAccount {
public static void main(String[] args) {
BankAccount account = new BankAccount();
// Setting account details
account.setAccountNumber("123456789");
account.deposit(1000); // Depositing money
// Checking balance
System.out.println("Account Number: " + account.getAccountNumber());
System.out.println("Balance: $" + account.getBalance());
// Withdrawing money
account.withdraw(500);
System.out.println("Updated Balance: $" + account.getBalance());
// Attempting an invalid withdrawal
account.withdraw(600); // This will trigger the validation message
}
}
```
Explanation:
- **Encapsulation** ensures that the `accountNumber` and `balance` are only modified through setter
methods and controlled operations like `deposit()` and `withdraw()`.
- The `withdraw()` method checks if the withdrawal amount is valid before proceeding.
- This example shows how encapsulation is useful in real-world scenarios like banking, where data
protection and validation are crucial.
Example 4: Car Details
This example encapsulates the details of a car (model and speed), and speed is regulated using setter
methods.
Code:
package encapsulation;
class Car {
private String model;
private int speed;
// Getter for model
public String getModel() {
return model;
}
// Setter for model
public void setModel(String model) {
this.model = model;
}
// Getter for speed
public int getSpeed() {
return speed;
}
// Setter for speed with validation
public void setSpeed(int speed) {
if (speed >= 0 && speed <= 200) {
this.speed = speed;
} else {
System.out.println("Speed must be between 0 and 200 km/h.");
}
}
}
public class TestCar {
public static void main(String[] args) {
Car car = new Car();
// Setting car details
car.setModel("Tesla Model S");
car.setSpeed(150);
// Getting car details
System.out.println("Car Model: " + car.getModel());
System.out.println("Car Speed: " + car.getSpeed() + " km/h");
// Trying to set invalid speed
car.setSpeed(250); // This will trigger the validation message
}
}
```
#### Explanation:
- **Encapsulation** is used to protect the `model` and `speed` fields.
- The `setSpeed()` method ensures that the car's speed stays within a valid range (0 to 200 km/h).
- This example demonstrates how encapsulation can be used to enforce rules and constraints on class
data.
---
In all these examples, encapsulation provides control over how fields are accessed and modified,
ensuring data integrity and allowing validation where needed.