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.
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:
Data hiding: Class fields are made private to prevent direct access from outside the class.
Controlled access: Public methods (getters and setters) are used to access and modify private fields.
Syntax of encapsulation
class ClassName {// Private data membersprivate DataType fieldName;// Public getter methodpublic DataType getFieldName() {return fieldName;}// Public setter methodpublic void setFieldName(DataType fieldName) {this.fieldName = fieldName;}}
Explanation:
Private fields: Class fields are declared
privateto restrict direct access.Getter methods: Public methods are provided to access the private fields. They usually start with
getfollowed by the field name.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 membersprivate String accountHolderName;private double balance;// Constructor to initialize account detailspublic 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 accountHolderNamepublic String getAccountHolderName() {return accountHolderName;}// Getter for balancepublic double getBalance() {return balance;}// Method to deposit moneypublic 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 moneypublic 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 BankAccountBankAccount account = new BankAccount("John Doe", 1000);// Accessing account details and performing transactionsSystem.out.println("Account Holder: " + account.getAccountHolderName());System.out.println("Balance: " + account.getBalance());// Deposit moneyaccount.deposit(500);System.out.println("Updated Balance: " + account.getBalance());// Withdraw moneyaccount.withdraw(300);System.out.println("Updated Balance: " + account.getBalance());}}
Explanation
Line 1–4: The
BankAccountclass encapsulates account details using private fields:accountHolderNameandbalance.Line 17–24: Public getter methods (
getAccountHolderNameandgetBalance) provide read-only access to the private fields.Line 27–24: The
depositandwithdrawmethods allow controlled modifications of the balance, ensuring validation rules are applied.Line 47–64: The
mainclass demonstrates how encapsulation enables safe and controlled interaction with theBankAccountclass.
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
Encapsulation ensures data security and controlled access in Java by hiding fields and providing methods to interact with them.
Use access modifiers to restrict field visibility and public methods to define how they can be accessed or modified.
Encapsulation improves maintainability, reusability, and modularity in object-oriented design.
It is widely used in real-world applications like banking, healthcare, and e-commerce systems to manage sensitive data effectively.
If fields are not declared as
private, they can be directly accessed and modified by subclasses, breaking encapsulation.Use
protectedonly when a clear subclassing relationship exists and the functionality needs to be extended. Otherwise, preferprivatefor 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?
What is encapsulation with an example?
What is the difference between abstraction and encapsulation?
What is a real-time example of encapsulation in Java?
Free Resources