How to use encapsulation in Java

Encapsulation promotes data security, maintainability, and reusability. It ensures that the internal workings of a class are hidden from external interaction and that only controlled access is provided through methods.

Suppose a banking system where customer details, such as account number and balance, need to be kept private. Customers should only be allowed to view their balance and perform limited actions like depositing or withdrawing money, based on predefined rules.

Note: Encapsulation allows us to achieve this by keeping sensitive data private and providing controlled access to it through methods.

What is encapsulation in Java?

Encapsulation is a way to protect sensitive data in a class by restricting direct access and allowing controlled interaction through methods. It uses access modifiers like private, protected, and public to control the visibility of class members.

Key characteristics of encapsulation:

  1. Data hiding: Class fields are made private to prevent direct access from outside the class.

  2. Controlled access: Public methods (getters and setters) are used to access and modify private fields.

Syntax of encapsulation

class ClassName {
// Private data members
private DataType fieldName;
// Public getter method
public DataType getFieldName() {
return fieldName;
}
// Public setter method
public void setFieldName(DataType fieldName) {
this.fieldName = fieldName;
}
}

Explanation:

  1. Private fields: Class fields are declared private to restrict direct access.

  2. Getter methods: Public methods are provided to access the private fields. They usually start with get followed by the field name.

  3. Setter methods: Public methods are used to modify the private fields. They typically start with set. This ensures validation or logic can be applied before updating the field.

Now that we understand what encapsulation is, let’s look at how it’s implemented in Java.

Implementation of Java encapsulation

Consider a scenario where a bank account class encapsulates the account holder's information and provides controlled access.

class BankAccount {
// Private data members
private String accountHolderName;
private double balance;
// Constructor to initialize account details
public BankAccount(String accountHolderName, double initialBalance) {
this.accountHolderName = accountHolderName;
if (initialBalance > 0) {
this.balance = initialBalance;
} else {
System.out.println("Initial balance must be positive.");
}
}
// Getter for accountHolderName
public String getAccountHolderName() {
return accountHolderName;
}
// Getter for balance
public double getBalance() {
return balance;
}
// Method to deposit money
public void deposit(double amount) {
if (amount > 0) {
balance += amount;
System.out.println("Deposited: " + 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;
System.out.println("Withdrawn: " + amount);
} else {
System.out.println("Insufficient balance or invalid amount.");
}
}
}
public class main {
public static void main(String[] args) {
// Creating a new BankAccount
BankAccount account = new BankAccount("John Doe", 1000);
// Accessing account details and performing transactions
System.out.println("Account Holder: " + account.getAccountHolderName());
System.out.println("Balance: " + account.getBalance());
// Deposit money
account.deposit(500);
System.out.println("Updated Balance: " + account.getBalance());
// Withdraw money
account.withdraw(300);
System.out.println("Updated Balance: " + account.getBalance());
}
}

Explanation

  • Line 1–4: The BankAccount class encapsulates account details using private fields: accountHolderName and balance.

  • Line 17–24: Public getter methods (getAccountHolderName and getBalance) provide read-only access to the private fields.

  • Line 27–24: The deposit and withdraw methods allow controlled modifications of the balance, ensuring validation rules are applied.

  • Line 47–64: The main class demonstrates how encapsulation enables safe and controlled interaction with the BankAccount class.

Try this: Imagine you are building a payment system. Use encapsulation to design a Payment class that secures payment details like cardNumber and expiryDate, allowing only validated changes through methods.

Advantages and disadvantages of encapsulation

Advantages

Disadvantages

Sensitive data is protected from unauthorized access.

Encapsulation requires additional code for getters, setters, and validation.

Access to fields is controlled through getter and setter methods.

Method calls (e.g., getters and setters) can be slightly slower than direct field access.

Key takeaways

  1. Encapsulation ensures data security and controlled access in Java by hiding fields and providing methods to interact with them.

  2. Use access modifiers to restrict field visibility and public methods to define how they can be accessed or modified.

  3. Encapsulation improves maintainability, reusability, and modularity in object-oriented design.

  4. It is widely used in real-world applications like banking, healthcare, and e-commerce systems to manage sensitive data effectively.

  5. If fields are not declared as private, they can be directly accessed and modified by subclasses, breaking encapsulation.

  6. Use protected only when a clear subclassing relationship exists and the functionality needs to be extended. Otherwise, prefer private for stricter control.

Unlock your Java potential and take control of your coding journey! Start learning Java today to explore more than encapsulation, build Java-based applications, and become a Java developer now!

Frequently asked questions

Haven’t found what you were looking for? Contact Us


What is encapsulation in Java?

Encapsulation in Java is the process of wrapping data (fields) and methods into a single unit, typically by using classes, while restricting direct access to some components through access modifiers like private.


What is encapsulation with an example?

Encapsulation means using private variables with public getter and setter methods to control access. For example, a BankAccount class can use encapsulation to secure account details and provide controlled access to balance through methods.


What is the difference between abstraction and encapsulation?

Encapsulation focuses on bundling data and methods into a single unit and controlling access, while abstraction is about hiding implementation details and showing only relevant features. For more details, have a look at What is the difference between encapsulation and abstraction?.


What is a real-time example of encapsulation in Java?

A real-time example is a banking system where account details like balance and account holder name are private, and access is controlled through methods like getBalance() and deposit().


Free Resources

Copyright ©2025 Educative, Inc. All rights reserved