Encapsulation in Java – How to Implement it?

Encapsulation in Java – How to Implement it?

6 mins read540 Views Comment
Atul
Atul Harsha
Senior Manager Content
Updated on Jan 6, 2023 10:30 IST

In this blog, we will explore the concept of encapsulation in Java and how it is used to improve the structure and reliability of a program. We will cover the benefits of encapsulation, as well as how to implement it in your code using getter and setter methods. By the end of this blog, you will have a solid understanding of encapsulation and how it can help you write better, more maintainable code.

2023_01_Encapsulation-in-Java.jpg

Encapsulation in Java is bundling data and related methods together as a single unit. Encapsulation protects the data within a class by hiding it from other classes and only allowing it to be accessed through the methods of the class.

  • Encapsulation is a OOPS concept in Java which binds up data and methods within a single unit (called a class).
  • Instance variables in a class are hidden from other classes and can only be accessed through the methods of the class.
  • This helps to protect the data within a class and create a clear separation between the internal workings of the class and the external interface presented to other classes.
  • Encapsulation promotes modularity and maintainability within a program.

This helps to create a clear separation between the internal workings of a class and the external interface. As a result, encapsulation helps in modularity and maintainability within a program. It allows the developer to easily understand and modify different parts of the code independently.

Explore popular Java Courses

Why use Encapsulation in Java?

  • Protects data within a class from accidental modification
  • Allows code to be reused in different contexts
  • Improves the modularity of a program
  • Enhances security by limiting access to sensitive data and functions
  • Improves the structure and maintainability of a program
Recommended online courses

Best-suited Java courses for you

Learn Java with these high-rated online courses

– / –
6 weeks
15 K
3 months
– / –
170 hours
– / –
6 months
2.05 K
3 months
– / –
2 months
5.4 K
1 month
5.5 K
1 month
17 K
3 months

How to implement Encapsulation in Java?

To implement encapsulation in Java, you can follow these steps:

  • Declare the instance variables of a class as private to prevent them from being directly accessed or modified by other classes.
  • Provide public getter and setter methods to allow other classes to access and modify the private instance variables.
  • Access the private instance variables only through the getter and setter methods from within the class.

Encapsulation Syntax

 
public class MyClass {
// declare instance variables as private
private <data type> <variable name>;
...
// provide public getter and setter methods
public <data type> get<VariableName>() {
return <variable name>;
}
public void set<VariableName>(<data type> <variable name>) {
this.<variable name> = <variable name>;
}
// access private instance variables only through getter and setter methods
public void someMethod() {
<variable name> = get<VariableName>();
set<VariableName>(<new value>);
}
}
Copy code

Here, MyClass is the name of the class that you are implementing encapsulation in. You would replace <data type> with the data type of the instance variable (such as int, double, String, etc.), and <variable name> with the name of the variable. The getter and setter methods follow a standard naming convention, with the getter method starting with get and the setter method starting with set. The getter method returns the value of the instance variable, and the setter method sets the value of the instance variable to a new value.

By following this syntax, you can effectively encapsulate the data and behavior of a class and create a clear separation between its internal workings and the external interface that it presents to other classes.

Features of Java Programming Language
Data Types in Java – Primitive and Non-Primitive Data Types Explained
Conditional Statements in Java

Simple Example of Encapsulation in Java

Write a Java program to create a class that represents a bank account, with instance variables for the balance, account number, and owner name, and methods for depositing and withdrawing money, as well as accessing the account details. Ensure that the BankAccount details are not accessed and modified accidentally by other classes.

For this problem we will implement encapsulation in the BankAccount class. This will protect the instance variables and ensure that they can only be accessed and modified through the appropriate methods. Let’s see how,

 
public class BankAccount {
// instance variables for the bank account
private double balance; // the current balance of the account
private int accountNumber; // the account number
private String ownerName; // the name of the account owner
// constructor to initialize the account with given values
public BankAccount(double balance, int accountNumber, String ownerName) {
this.balance = balance;
this.accountNumber = accountNumber;
this.ownerName = ownerName;
}
// method to deposit money into the account
public void deposit(double amount) {
balance += amount;
}
// method to withdraw money from the account
public double withdraw(double amount) {
// check if the balance is sufficient for the withdrawal
if (balance < amount) {
return 0; // return 0 if not sufficient
}
balance -= amount;
return amount; // return the amount withdrawn
}
// method to get the current balance of the account
public double getBalance() {
return balance;
}
// method to get the account number
public int getAccountNumber() {
return accountNumber;
}
// method to get the name of the account owner
public String getOwnerName() {
return ownerName;
}
}
Copy code
  • The BankAccount class represents a bank account, with instance variables for the balance, account number, and owner name. These variables are hidden from other classes and can only be accessed through the methods of the BankAccount class.
  • The BankAccount class has a constructor that takes three arguments: the initial balance, account number, and owner name. This constructor is used to create a new BankAccount object and initialize its instance variables with the given values.
  • The BankAccount class has three methods for interacting with the account:
    • The deposit method adds a given amount of money to the account balance.
    • The withdraw method subtract a given amount of money from the account balance, if the balance is sufficient. If the balance is insufficient, then the method returns 0.
    • The getBalance, getAccountNumber, and getOwnerName methods return the current balance, account number, and owner name, respectively.
  • Each of these methods helps to encapsulate the data and behavior of the BankAccount class, allowing other classes to interact with the account in a safe and controlled manner.

Data Hiding vs. Encapsulation in Java

Data hiding is a specific aspect of encapsulation that refers to the process of hiding data within a class from other classes. On the other hand Encapsulation is a broader concept that refers to the process of bundling data and related methods together within a single unit, and includes data hiding as well as other techniques for creating a clear separation between the internal workings of a class and the external interface that it presents to other classes.

Data Hiding Encapsulation
Refers to the process of hiding data within a class from other classes. Refers to the process of bundling data and related methods together within a class
Achieved by declaring instance variables as private. Achieved using private instance variables and providing public getter and setter methods to allow other classes to access and modify the data.
Protects data within a class from accidental modification. Protects data from accidental modification and creates a clear separation between the internal workings of a class and the external interface that it presents to other classes.
Helps to improve the security of a program. Helps to improve the security, modularity, flexibility, and maintainability of a program.

Getter and Setter method in Java

In Java, getter and setter methods are used to get and set the values of private instance variables. They are also known as “accessor” and “mutator” methods, respectively.

To use getter and setter methods in Java, you can follow these steps:

  1. Declare the private instance variables that you want to get and set.
  2. Create getter and setter methods for each of the instance variables. Both must have same data type as of the variable.
    1. The getter method return the value of the variable.
    2. The setter method accept a parameter with the same data type and is used to set the value of the variable.
  3. Call the getter and setter methods from within the class or other classes.

Here is an example of how to use getter and setter methods in Java:

 
public class Student {
private String name;
private int age;
// getter method for the name variable
public String getName() {
return name;
}
// setter method for the name variable
public void setName(String name) {
this.name = name;
}
// getter method for the age variable
public int getAge() {
return age;
}
// setter method for the age variable
public void setAge(int age) {
this.age = age;
}
}
Copy code
  • The name and age variables are private.
  • Getter methods (getName() and getAge()) are used to return the values of the private variables.
  • Setter methods (setName(String name) and setAge(int age)) are used to set the values of the private variables.
  • The private variables can only be accessed or modified through the corresponding getter and setter methods.
About the Author
author-image
Atul Harsha
Senior Manager Content

Experienced AI and Machine Learning content creator with a passion for using data to solve real-world challenges. I specialize in Python, SQL, NLP, and Data Visualization. My goal is to make data science engaging an... Read Full Bio