Java Encapsulation – Master the Concept with Real-life Examples

The most adopted and popular programming language approach, structured programming approach, failed to show the desired results in terms of bug-free, easy-to-maintain, and reusable programs.

The programming approach, Object-Oriented approach (OOP), offers a new and powerful way to cope with this complexity. The approach of OOP is based on various concepts that help achieve its goal to overcome the drawbacks of structured programming approaches.

This article will introduce you to one of the most fundamental concepts in OOP that is Encapsulation in Java.

Moving forth in this article, we are going to learn in detail about –

  1. What is Java Encapsulation?
  2. Encapsulation in the Real-World
  3. Encapsulation- A way to implement Abstraction
  4. Achieving Encapsulation in Java
  5. Advantages of Java Encapsulation

What is Java Encapsulation?

Encapsulation is one of the most powerful and fundamental concepts of Object-Oriented Programming. Encapsulation, in general, is the action of enclosing or binding something. In OOP, it is a way of combining both data and functions that operate on that data, into a single unit.

In other words, we can define it as Encapsulation is the wrapping up of data and functions (methods that operate on the data) into a single unit (called class).

There is a prohibition for direct access to the data. Functions (that combine with the data) are the only way to access data. These functions are the member functions or methods in Java. It basically creates a shield due to which the code or data cannot be accessed outside the shield.

If you want to read data items in an object, you call the member function in the object. It will read the data item from the function and return the value to you. You can’t access the data directly using the object. The data is hidden, so it is kept protected and safe from accidental alteration.

Data and its methods are said to be encapsulated into a single entity.

Get to know more about Java Methods in detail with Techvidvan.

The following figure shows the illustration of the approach of Encapsulation:

Java Encapsulation Approach

Encapsulation in the Real-world

Let us now consider the analogy to encapsulation in the real-world. In a large organization, there are so many departments like Sales, Accounts, Payroll, Purchase, Production, etc. Each department has its own personnel or staff that maintain its data.

Suppose an employee of the Production department wants to know the quantity of raw material that has been purchased for the next month. The employee would not be allowed to go through the data files of the Purchase dept.

Rather he will have to issue a memo to the ‘Purchase’ department requesting for the required information. Then some employees of the Purchase dept will go through the data files of Purchase and send the reply with the asked information.

This practice ensures that the users access the data accurately and the unexpert outsiders do not corrupt this data. Therefore we can say that the ‘data and employees’ of the department encapsulate together into a single entity, the Department.

Similarly, objects provide an approach to program organization while helping to maintain the integrity of the program data.

Encapsulation – A way to implement Abstraction

With the help of Encapsulation, we can apply data abstraction. Encapsulation hides the implementation details of the object.

We can often achieve Encapsulation through data/information hiding. Data/Information hiding is the process of hiding all the unessential characteristics of an object and showing only the necessary details.

The structure of the object, as well as the implementation of its methods, are invisible to users.

In the above example of the department, the essential information of the departments is visible that is dept-name, dept-head, number-of-employees, etc. The secret information which is not essential is not visible that is dept-profit/loss, stock, etc.

This information is available only if there request through a proper channel example, issuing a memo, etc.

Java Encapsulation

Achieving Encapsulation in Java

In order to achieve encapsulation in Java, we have to −

  • declare the variables of a class as private, so that they cannot be accessed directly from outside the class.
  • provide setter and getter methods that are declared as public, to view and change the values of the variables.

Dive a little deep into the concept of Java Variables and know more about it.

Now, we will see the practical implementation of encapsulation in the following program:

Code to explain the concept of Encapsulation in Java:

package com.techvidvan.encapsulation;

public class Encapsulation
{
  //Declaring the variables as private
  private String techVidvanName;
  private String techvidvanProfile;
  private int techVidvanAge;

  //declaring 'public' Setter and Getter Methods
  public void setName(String techVidvanName)
  {
    this.techVidvanName = techVidvanName;
  }
  public String getName()
  {
    return techVidvanName;
  }

  public void setProfile(String techVidvanProfile)
  {
    this.techvidvanProfile = techVidvanProfile;
  }
  public String getProfile()
  {
    return techvidvanProfile;
  }

  public void setAge(int techVidvanAge)
  {
    this.techVidvanAge = techVidvanAge;
  }
  public int getAge()
  {
    return techVidvanAge;
  }

  public static void main (String[] args)
  {
    Encapsulation obj = new Encapsulation();

    // setting values of the variables through setter methods
    obj.setName("Avina Garg");
    obj.setAge(22);
    obj.setProfile("Research Analyst Intern");

    // Displaying values of the variables through Getter methods
    System.out.println("Name of the employee: " + obj.getName());
    System.out.println("Age of the employee: " + obj.getAge());
    System.out.println("Profile of the employee: " + obj.getProfile());
  }
}

Output:

Name of the employee: Avina Garg
Age of the employee: 22
Profile of the employee: Research Analyst Intern

In the above code, we have three variables or data members techVidvanName, techVidvanAge, and techVidvanProfile. We have created separate setter and getter methods for all the variables and used these variables inside the same methods.

Setter methods set the value of the variable, while Getter methods are used to get or return the values.

Advantages of Java Encapsulation

Advantages of Java Encapsulation

We have already seen how important and essential the concept of Encapsulation is in Object-Oriented Programming. There are more benefits of using Encapsulation in Java which we are going to discuss below.

1. Data Hiding – Encapsulation allows the programmer to hide the inner classes in Java and to give access only to the desired codes to the users. It also gives the facility to the developer to not allow the users to know how the data and variables are stored.

2. Getter and Setter Methods – We can access private members-only within the same class. A class that is present outside this class can not access the private data members. If you need to access these private variables, you have to use public “setter” and “getter” methods.

3. Flexibility and Maintainability – With the help of encapsulation, we can make the fields of the class as write-only (If we only define the setter methods in the class) or read-only (If we only define the getter methods in the class) according to our requirements. It enhances the flexibility and maintainability of the code.

For e.g. in the above code, the implementation code of void setName (String name) and String getName() can be changed at any point in time.

4. Code Reusability – It allows the programmer or a user to effectively use the existing code again and again.

5. Total Control – A class can have total control over what is stored in its variables and fields.

6. Ease of Testing – With encapsulation, the testing becomes very easy. So, it is much better for Unit testing.

Summary

Encapsulation is one of the core features of Object-Oriented Programming. This feature introduces the concept of ‘Data hiding’. Every Java programmer should know how to implement the concept of Encapsulation.

Coming to the end of this article, we discussed the detailed and conceptual description of Java Encapsulation with the real-world example, so that you can easily relate it with the real world analogy.

We also covered the program to implement the encapsulation in Java. We understood the advantages of using Encapsulation in our programs to make them more flexible and effective.

Thank you for reading our article. Do share your feedback through the comment section below.

TechVidvan Team

The TechVidvan Team delivers practical, beginner-friendly tutorials on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. Our experts are here to help you upskill and excel in today’s tech industry.