Encapsulation In Java: Complete Tutorial With Examples

By Sruthy

By Sruthy

Sruthy, with her 10+ years of experience, is a dynamic professional who seamlessly blends her creative soul with technical prowess. With a Technical Degree in Graphics Design and Communications and a Bachelor’s Degree in Electronics and Communication, she brings a unique combination of artistic flair…

Learn about our editorial policies.
Updated March 7, 2024

Learn about Encapsulation in Java with examples, why we need it, associated getter and setter methods:

In this tutorial, we will discuss another OOP concept – “Encapsulation”. OOP has four pillars namely, abstraction, encapsulation, polymorphism, and inheritance.

While abstraction is used to expose only the relevant details to the end-user, encapsulation mainly deals with data security. In ensuring data security, encapsulation shields the data members from unwanted access by specifying access modifiers and also bundles the data into a single unit.

=> Check Out The Perfect Java Training Guide Here.

Encapsulation in Java

So how can we define Encapsulation in Java?

Definition of Encapsulation

“Encapsulation in Java can be defined as a mechanism using which the data and the methods that work on that data is wrapped to form a single unit.”

What Is Encapsulation In Java

Using encapsulation we can also hide the class data members (variables) from the other classes. These data member variables can be accessed indirectly using methods of the class in which they are declared. The methods in turn are accessed using the object of that class.

So what we conclude from the above definition is that we have hidden the data member variables inside a class and have also specified the access modifiers so that they are not accessible to the other classes.

Thus encapsulation is also a kind of “data hiding” although later in the tutorial we will see that encapsulation is not the same as data hiding.

encapsulation

The above figure represents a class which is an encapsulation unit that bundles the data and methods operating on this data into a single unit.

As encapsulation mainly deals with data, it is alternatively called “Data encapsulation”.

We can visualize encapsulation as a medical capsule. As we all know the medicine is enclosed inside a medical capsule. Similarly, data and methods are enclosed in a single unit in encapsulation.

Thus encapsulation acts as a protective shield around the data and prevents the data from unauthorized access by the outside world. In other words, it protects the sensitive data of our application.

In Java, there are two steps to implement encapsulation. Following are the steps:

  • Use the access modifier ‘private’ to declare the class member variables.
  • To access these private member variables and change their values, we have to provide the public getter and setter methods respectively.

Let’s now implement the example of encapsulation in Java.

Java Encapsulation Example

//Student_Id and name bundled in a unit "Student" => encapsulation
class Student {
    private int Student_Id;
    private String name;
    //getters, setters for Student_Id and name fields.
    public int getId() {
        return Student_Id;
    }
    public void setId(int s_id) {
        this.Student_Id = s_id;
    }
    public String getname() {
        return name;
    }
    public void setname(String s_name) {
        this.name = s_name;
    }
}
class Main{
    public static void main(String[] args) {
        //create an object of Student class
        Student s=new Student();
        //set fields values using setter methods
        s.setId (27);
        s.setname("Tom Lee");
        //print values using getter methods        
        System.out.println("Student Data:" + "\nStudent ID:" + s.getId()
                            + " Student Name:" + s.getname());
    }
}

Output:

Output - Encapsulation Example

In the above program, we declare a class which is the encapsulation unit. This class Student has bundled the data (Student_Id and name) and the methods to read and set values for these members into a single unit.

Note the access modifiers associated with the member fields. Both the member fields are private so that they are not accessible outside the Student class.

We provide getters (getId and getname) to read the values of these fields and setter methods (setId and setname) to set values for these methods. This is the only access they have and that also should be done using the Student class object.

Getter And Setter Methods

To implement encapsulation in Java, we make the data member variables of the class as private. Now, these private variables are not accessible to anything outside the class including the class object.

This means if we have a class ABC as follows.

class ABC{

private int age;

}

Let’s create an object of class ABC as follows:

ABC abc = new ABC ();

abc.age = 21; //compiler error

So in the above code, accessing the private variable using the class object will result in a compiler error.

To access the private variables and read their values & set some new values in them, we need some way to do this. Thus Java provides a way to access private variables using getter and setter methods.

Getter and Setters are public methods that we can use to create, modify, delete, or simply view the values of the private variables.

The below program is an example of Getter and Setter methods.

//Account class - private data members bundled with getters and setters
class Account {  
    //private data members  
    private long acc_no;  
    private String name,email;  
    private float amount;  
   
  //public getter and setter methods for each data member 
    public long getAcc_no() {  
        return acc_no;  
    }  
    public void setAcc_no(long acc_no) {  
        this.acc_no = acc_no;  
    }  
    public String getName() {  
        return name;  
    }  
    public void setName(String name) {  
        this.name = name;  
    }  
    public String getEmail() {  
        return email;  
    }  
    public void setEmail(String email) {  
        this.email = email;  
    }  
    public float getAmount() {  
        return amount;  
    }   
    public void setAmount(float amount) {  
        this.amount = amount;  
    }  
  
}  public class Main {  
    public static void main(String[] args) {  
        //create instance of Account class  
        Account myAcc=new Account();  
        //set values for data members through setter methods  
        myAcc.setAcc_no(775492842L);  
        myAcc.setName("SoftwareTestingHelp.com");  
        myAcc.setEmail("sth_account@sth.com");  
        myAcc.setAmount(25000f);  
        //read data member values through getter methods  
        System.out.println("Account No:" + myAcc.getAcc_no()+" "+"Account Name:" 
                + myAcc.getName()+" \n"+"Account holder email:" + myAcc.getEmail()+"\n "
                + "Amount in Account:" + myAcc.getAmount());  
    }  
}  

Output:

getter and setter methods - output

The above program has a class Account and it has four private variables related to the account. As all the data members are private we have provided the getter and setter methods for each of these variables.

In the main method, we read and set values for these private variables using the public getter and setter methods accessed through the object of the class Account.

Data Hiding In Java

Frequently, we use encapsulation and data hiding interchangeably. But both are not the same. Java encapsulation deals with grouping of related data into a single unit to ensure better management and security of data.

Data hiding on the other hand restricts the data member access by hiding the implementation details. Although encapsulation is not exactly data hiding, it provides us the way of data hiding. Data hiding is achieved using access modifiers.

Java provides four access modifiers.

  • public: Accessible to everyone.
  • private: Accessible only within the class.
  • protected: Accessible to the containing package and the subclasses.
  • default: Accessible within the package.

Encapsulation bundles the data in a single unit, so in a way, it hides the data. Also, it makes the data private and thus is inaccessible to the outside world. For making the data private, we use the access modifier private which is a data hiding concept.

At the same time, only the relevant details are provided to the end-user without exposing the implementation details which is a definition of abstraction. Thus we can view encapsulation as a combination of abstraction as well as data-hiding.

Why Do We Need Encapsulation

There are various reasons as to why encapsulation is essential in Java:

  • Encapsulation allows us to modify the code or A part of the code without having to change any other functions or code.
  • Encapsulation controls how we access data.
  • We can modify the code based on the requirements using encapsulation.
  • Encapsulation makes our applications simpler.

Frequently Asked Questions

Q #1) Why Is Encapsulation used in Java?

Answer: Encapsulation in Java is mostly useful to hide the data. Or in other words, to decide about the access given to data as to who can access it, and who cannot.

Q #2) What is Encapsulation in OOP?

Answer: Encapsulation is one of the important pillars of Object-oriented programming language and it deals with the bundling of data and methods operating on that data into a single unit. For example, a class in Java is an encapsulated structure. Encapsulation also deals with decisions regarding providing access to data.

Q #3) What is the advantage of Encapsulation in Java?

Answer: The major advantage of encapsulation in Java is data hiding. Using encapsulation we can allow the programmer to decide on the access to data and methods operating on that data. For example, if we want a particular piece of data to be inaccessible to anyone outside the class, then we make that data private.

Q #4) What is the Encapsulation process?

Answer: Encapsulation is a process of picking up data from one format or protocol (in networking terms) and translating or reformatting it into another format or protocol so that the data is accessible across the applications or network and at the same time it is protected.

Q #5) What is the last step in data encapsulation?

Answer: The last step in encapsulation is changing the user information into equivalent data. Then this data is changed into segments that are further transformed into data packets. Data packets are placed into a logical frame that can be transferred to and fro in the software environment

Conclusion

This concludes our tutorial on Encapsulation in Java. Encapsulation is a technique of bundling up of member variables and the methods operating on these data members into a single unit. A class in Java is a classic example of encapsulation as it wraps the data and methods into a single unit.

Java achieves encapsulation implementation by making all the data members private and then providing getter and setter methods that are public so that we can read the values of the private variables and set new values for these variables.

=> Visit Here For The Exclusive Java Training Tutorial Series.

Was this helpful?

Thanks for your feedback!

Leave a Comment