Skip to main content

Java Encapsulation

What is Encapsulation in Java?

Encapsulation is one of the four fundamental Object-Oriented Programming (OOP) concepts. The other three are inheritance, polymorphism, and abstraction. Encapsulation in Java is a mechanism of wrapping the data (variables) and code acting on the data (methods) together as a single unit. In other words, encapsulation can be defined as a protective shield that stops the data from being accessed by the code outside this shield.

Advantages of Encapsulation

The benefits of encapsulation include:

  1. Data Hiding: The user will have no idea about the inner implementation of the class. It will not be visible to the user how the class is stored values in the variables. He only knows that we are passing the values to a setter method and variables are getting initialized with that value.
  2. Increased Flexibility: We can make the variables of the class read-only or write-only depending on our requirement. If we wish to make the variables as read-only then we have to omit the setter methods like setName(), setAge(), etc. from the above program or if we wish to make the variables as write-only then we have to omit the get methods like getName(), getAge(), etc. from the above program.
  3. Reusability: Encapsulation also improves the re-usability and easy to change with new requirements.
  4. Testing code is easy: Encapsulated code is easy to test for unit tests.

How to achieve Encapsulation in Java?

There are two steps to achieve encapsulation in Java:

  1. Declare the variables of a class as private.
  2. Provide public setter and getter methods to modify and view the variable values.

Example of Encapsulation in Java

Here's a simple example of encapsulation that has only one field with its setter and getter methods:

public class Employee {

private String name;

public String getName() {
return name;
}

public void setName(String newName) {
name = newName;
}
}

In the above class, the name data is hidden as it's declared private. This field can be accessed only via the methods getName() and setName(). So, the data can be accessed only through these methods, making the name field encapsulated in the class.

Remember, encapsulation in Java is a preventative measure to protect the data from outside interference and misuse.

Conclusion

In conclusion, encapsulation in Java is a critical aspect of object-oriented programming. It allows us to hide the internal workings of a class and protect our data from unauthorized access and modification. It enhances security and makes our code more manageable and flexible, which aids in the easy maintenance and testing of our application. Thus, learning and utilizing encapsulation is a significant step in becoming an effective Java programmer.