In this tutorial, we have compiled the top 6 encapsulation programs in Java for practice. Each program is explained step by step in a simple and beginner-friendly way so that you can easily understand how encapsulation works in Java.
These Java encapsulation programming exercises are also useful for Java coding practice, exams, viva, and technical interviews. Practicing these examples will help you understand how private data members, constructors, getter methods, and setter methods are used to implement encapsulation in Java.
If you are new to the concept of encapsulation or have any doubts about it, I recommend reading our detailed tutorial on encapsulation in Java first. It explains the concept from the basics and will make the programs given below much easier to understand.
Java Encapsulation Program Using Getter and Setter
In this Java program, we will learn how to implement encapsulation by declaring an instance variable as private and providing public getter and setter methods to access and modify it.
Because the private variable cannot be accessed directly from outside the class, we use the setter method to assign its value and the getter method to retrieve it.
Example Program 1:
class Number {
// Declare the instance variable as private (data hiding)
private int y;
// Public getter method to retrieve the value of y
public int getY() {
return y;
}
// Public setter method to update the value of y
public void setY(int y) {
this.y = y;
}
}
public class Encaptest {
public static void main(String[] args) {
// Create an instance of the Number class
Number n = new Number();
// Call the setter method to assign a value
n.setY(6);
// Call the getter method to read the value
int num = n.getY();
// Display the retrieved value
System.out.println(num);
}
}Output:
6
This example program demonstrates the basic implementation of data hiding and controlled access in Java. In this example:
- Declaring Private Data: The variable y is marked as private inside the Number class. This hides it completely from other classes, preventing direct and unauthorized access (for example, writing n.y = 6 outside the class will cause an error).
- Creating the Getter Method: The getY() method is public, meaning anyone can access it. Its only job is to return the current value of y so that other classes can read it safely.
- Creating the Setter Method: The setY(int y) method is also public. It takes a number as an input and assigns it to the private variable using this.y = y.
- Creating the Object: Inside the main method, Number n = new Number(); creates a new object of the Number class in memory.
- Writing Data (Calling the Setter): Instead of modifying y directly, n.setY(6); passes the value 6 to the setter method, which stores it securely inside y.
- Reading Data (Calling the Getter): int num = n.getY(); calls the getter method to fetch the value of y (which is 6) and stores it in a new local variable named num.
- Printing the Result: System.out.println(num); prints 6 to the console, confirming that the value was successfully written and retrieved through encapsulation.
Java Encapsulation Program with Data Validation
Encapsulation does more than just hide data—it gives you complete control over how variables are updated. By applying validation rules inside setter methods, you can prevent invalid, corrupted, or out-of-range values from being assigned to object fields.
In this example, we encapsulate a BankAccount class to ensure the account balance cannot be set to a negative number.
Example Program 2:
class BankAccount {
// Declare the balance field as private (Data Hiding)
private double balance;
// Getter method to retrieve the current balance
public double getBalance() {
return balance;
}
// Setter method with validation logic
public void setBalance(double balance) {
if (balance >= 0) {
this.balance = balance;
System.out.println("Success: Balance updated to $" + balance);
} else {
System.out.println("Error: Balance cannot be negative. Value not updated.");
}
}
}
public class ValidationTest {
public static void main(String[] args) {
// Create an instance of BankAccount
BankAccount account = new BankAccount();
// 1. Attempt to assign a valid balance
System.out.println("Setting balance to 500.0...");
account.setBalance(500.0);
System.out.println("Current Balance: $" + account.getBalance());
System.out.println("-----------------------------------");
// 2. Attempt to assign an invalid (negative) balance
System.out.println("Setting balance to -150.0...");
account.setBalance(-150.0);
System.out.println("Current Balance: $" + account.getBalance());
}
}Output:
Setting balance to 500.0... Success: Balance updated to $500.0 Current Balance: $500.0 ----------------------------------- Setting balance to -150.0... Error: Balance cannot be negative. Value not updated. Current Balance: $500.0
In this example:
- Validation in Setter (setBalance): Before updating the field, an
if (balance >= 0)condition checks whether the input meets business requirements.- If valid,
this.balance = balance;executes and saves the new amount. - If invalid, the method rejects the assignment and prints an error message, preserving the previous balance.
- If valid,
- Controlled Read Access (getBalance): The getBalance() method allows other classes to access the current balance without risking unintended modifications.
- Preserving Data Integrity: When the second call attempts to pass -150.0, the setter filters it out, keeping the balance secure at $500.0.
Java Encapsulation Program Using Constructor, Getter, and Setter
In this Java program, we will implement full encapsulation using a Rectangle class. The length and breadth variables are declared as private, which prevents direct access to them from outside the class.
A parameterized constructor is used to initialize the values of length and breadth. Public getter methods are then used to retrieve these values, while setter methods are used to modify them.
Example Program 3:
class Rectangle
{
// Declare instance variables as private in the class.
private int length;
private int breadth;
// Declare a constructor Rectangle and define parameters of constructor.
Rectangle(int length, int breadth)
{
this.length = length;
this.breadth = breadth;
}
// Create a getter method for each private variable.
public int getLength()
{
return length;
}
public int getBreadth()
{
return breadth;
}
// Create a setter method for each private variable and define the parameter.
public void setLength(int length)
{
this.length = length;
}
public void setBreadth(int breadth)
{
this.breadth = breadth;
}
}
public class RectangleTest {
public static void main(String[] args)
{
// Create an object of class Rectangle and assign values of the parameter used in constructor.
Rectangle rt = new Rectangle(20,30);
// Call getter method to read value of variable because we cannot read the value directly due to privacy.
int lth = rt.getLength();
int bth = rt.getBreadth();
// Calculate area of the rectangle and print it on the console.
int Area = lth * bth;
System.out.println("Area: " +Area);
// Let's update the new value of variable using setter method.
rt.setLength(50);
rt.setBreadth(60);
// Call getter method to read the updated value.
int ln = rt.getLength();
int br = rt.getBreadth();
int newArea = ln * br;
System.out.println("New area: " +newArea);
}
}Output:
Area: 600 New area: 3000
Initially, the program creates a Rectangle object with a length of 20 and a breadth of 30. It retrieves these values through getter methods and calculates the area of the rectangle.
The program then updates the length to 50 and the breadth to 60 using setter methods. Finally, it retrieves the updated values and calculates the new area.
Creating a Read-Only Class Using Getter Method
A class is made read-only by providing only getter methods and initializing the values through a constructor. Once the object is created, its values cannot be modified from the outside.
Example Program 4:
// A Read-Only Player class
class Player {
// Private instance variables
private String pName;
private int pAge;
private String gameType;
// Constructor to initialize all fields at object creation
public Player(String pName, int pAge, String gameType) {
this.pName = pName;
this.pAge = pAge;
this.gameType = gameType;
}
// Getter methods only (Read-Only access)
public String getPName() {
return pName;
}
public int getPAge() {
return pAge;
}
public String getGameType() {
return gameType;
}
}
public class PlayerTest {
public static void main(String[] args) {
// Create an instance of the Read-Only class
Player ply = new Player("Sachin", 40, "Cricket");
// Read data using getter methods
String plyName = ply.getPName();
int plyAge = ply.getPAge();
String plyGameType = ply.getGameType();
// Display the output
System.out.println("Player's Name: " + plyName);
System.out.println("Player's Age: " + plyAge);
System.out.println("Player's Gametype: " + plyGameType);
}
}Output:
Player's Name: Sachin Player's Age: 40 Player's Gametype: Cricket
This example program demonstrates how Java encapsulation can be used to restrict modification of data by creating read-only fields and providing controlled read access through getter methods.
In this example:
- The Player class contains three private variables: pName, pAge, and gameType.
- The values of these private variables are initialized through a parameterized constructor.
- Unlike a typical encapsulated class, no setter methods are provided. Therefore, after the object is created, the values cannot be modified through public setter methods.
- Public getter methods are provided to retrieve the values of the private fields. As a result, the fields can be read from outside the class but cannot be directly modified.
- In the main() method, a Player object is created with the values “Sachin”, 40, and “Cricket”.
- The getter methods are then used to display the player’s information.
Creating a Write-Only Class Using Setter Method
A class is made write-only by providing setter methods to assign or modify the values of its private data members without providing public getter methods to read those values directly. This approach allows values to be entered from outside the class but prevents them from being directly read through public methods.
For example, a class may accept a password, security token, or other sensitive value through a setter method while preventing outside code from directly retrieving the stored value through a getter method.
Example Program 5:
// A Write-Only Password/Credentials class
class UserAccount {
// Private field
private String password;
// Setter method only (No getter method provided)
public void setPassword(String password) {
if (password.length() >= 8) {
this.password = password;
System.out.println("Success: Password updated securely.");
} else {
System.out.println("Error: Password must be at least 8 characters long.");
}
}
}
public class WriteOnlyTest {
public static void main(String[] args) {
UserAccount user = new UserAccount();
// Write access is allowed
user.setPassword("Admin@1234");
// user.password; // Compile-time Error: password has private access
// user.getPassword(); // Compile-time Error: Method getPassword does not exist
}
}Output:
Success: Password updated securely.
This example demonstrates how encapsulation controls data modification from outside the class while keeping the internal data members completely private. In this example:
- The variable password is marked as private to hide the sensitive data. This ensures that outside classes cannot read or view the password directly.
- The class includes only a public setter method (setPassword) to make it write-only access. This means external classes are allowed to set or update the password, but they have no way to retrieve or display it.
- The class does not provide a getter method to retrieve value directly.
- Inside the setPassword() method, an
if (password.length() >= 8)validates the password before writing. It ensures the password meets security requirements before saving it. If the password is too short, it gets rejected. - When validation passes,
this.password = password;safely stores the new password inside the class instance.
Real-World Example: Bank Account Management System in Java
A good real-world example of encapsulation is a bank account in a banking application. In a real banking software project, account information such as the account number, account holder’s name, and balance should not be directly accessible or modified by other parts of the application.
To achieve this, the data members can be declared as private and accessed through carefully designed public methods. For example, instead of allowing another class to directly change the account balance, the deposit() and withdraw() methods can control how the balance is updated.
The withdraw() method can also check whether the customer has sufficient balance before allowing the transaction. This prevents invalid operations and keeps the account data under the control of the BankAccount class.
This is the practical example of encapsulation in Java, which hides an object’s internal data and provides controlled access to that data through methods.
Example Program 6:
class BankAccount {
private String accountNumber;
private String accountHolderName;
private double balance;
// Constructor
public BankAccount(String accountNumber, String accountHolderName, double initialBalance) {
this.accountNumber = accountNumber;
this.accountHolderName = accountHolderName;
if (initialBalance >= 0) {
this.balance = initialBalance;
} else {
this.balance = 0;
}
}
// Getter method for account number
public String getAccountNumber() {
return accountNumber;
}
// Getter method for account holder name
public String getAccountHolderName() {
return accountHolderName;
}
// Getter method for balance
public double getBalance() {
return balance;
}
// Deposit money
public void deposit(double amount) {
if (amount > 0) {
balance = balance + amount;
System.out.println("Amount deposited: ₹" + amount);
} else {
System.out.println("Invalid deposit amount.");
}
}
// Withdraw money
public void withdraw(double amount) {
if (amount <= 0) { System.out.println("Invalid withdrawal amount."); } else if (amount > balance) {
System.out.println("Insufficient balance.");
} else {
balance = balance - amount;
System.out.println("Amount withdrawn: ₹" + amount);
}
}
}
public class BankAccountTest {
public static void main(String[] args) {
BankAccount account = new BankAccount("ACC1001", "Rahul", 10000);
System.out.println("Account Number: " + account.getAccountNumber());
System.out.println("Account Holder: " + account.getAccountHolderName());
System.out.println("Initial Balance: ₹" + account.getBalance());
account.deposit(5000);
System.out.println("Balance after deposit: ₹" + account.getBalance());
account.withdraw(3000);
System.out.println("Balance after withdrawal: ₹" + account.getBalance());
account.withdraw(20000);
System.out.println("Final Balance: ₹" + account.getBalance());
}
}Output:
Account Number: ACC1001 Account Holder: Rahul Initial Balance: ₹10000.0 Amount deposited: ₹5000.0 Balance after deposit: ₹15000.0 Amount withdrawn: ₹3000.0 Balance after withdrawal: ₹12000.0 Insufficient balance. Final Balance: ₹12000.0
In this example:
- The BankAccount class represents a customer’s bank account in a banking application.
- The class contains three data members: accountNumber, accountHolderName, and balance.
- These data members are declared as private:
- private String accountNumber;
- private String accountHolderName;
- private double balance;
- This prevents other classes from directly accessing or modifying the account information.
- A parameterized constructor is used to initialize the account number, account holder’s name, and initial balance when a BankAccount object is created.
- The constructor also checks whether the initial balance is valid. If a negative balance is supplied, the balance is set to 0.
- The getAccountNumber(), getAccountHolderName(), and getBalance() methods are getter methods. They provide controlled access to the private data members.
- There is no setBalance() method. This is intentional because the balance should not be changed directly from outside the class.
- The deposit() method is used to add money to the account. It first checks whether the deposit amount is greater than zero.
- The withdraw() method is used to withdraw money from the account. It checks whether the withdrawal amount is valid and whether sufficient balance is available.
- If the withdrawal amount is greater than the available balance, the transaction is rejected and an “Insufficient balance.” message is displayed.
- The program first displays the customer’s account information and initial balance. It then deposits ₹5000 into the account and displays the updated balance.
- Next, it withdraws ₹3000 and displays the remaining balance.
- Finally, the program attempts to withdraw ₹20000. Since the available balance is insufficient, the withdrawal is not performed.




