Encapsulation in Java
Encapsulation is a fundamental concept in object-oriented programming (OOP) that refers to the bundling of data and methods that operate on that data within a single unit, which is called a class in Java. Encapsulation is a way of hiding the implementation details of a class from outside access and only exposing a public interface that can be used to interact with the class.
In Java, encapsulation is achieved by declaring the instance variables of a class as private, which means they can only be accessed within the class. To allow outside access to the instance variables, public methods called getters and setters are defined, which are used to retrieve and modify the values of the instance variables, respectively. By using getters and setters, the class can enforce its own data validation rules and ensure that its internal state remains consistent.
Advantage of Encapsulation in Java
- By providing only a setter or getter method, you can make the class read-only or write-only. In other words, you can skip the getter or setter methods.
- It provides you the control over the data. Suppose you want to set the value of id which should be greater than 100 only, you can write the logic inside the setter method. You can write the logic not to store the negative numbers in the setter methods.
- It is a way to achieve data hiding in Java because other class will not be able to access the data through the private data members.
- The encapsulate class is easy to test. So, it is better for unit testing.
- The standard IDE’s are providing the facility to generate the getters and setters. So, it is easy and fast to create an encapsulated class in Java.
Simple Example of Encapsulation in Java
Let’s see the simple example of encapsulation that has only one field with its setter and getter methods.
1st File: Student.java
2nd File: Test.java
Output:
Advantages of Encapsulation
- Data Protection: The program runner will not be able to identify or see which methods are present in the code. Therefore he/she doesn’t get any chance to change any specific variable or data and hinder the running of the program.
- Flexibility: The code which is encapsulated looks more cleaner and flexible, and can be changed as per the needs. We can change the code read-only or write-only by getter and setter methods. This also helps in debugging the code if needed.
- Reusability: The methods can be changed and the code is reusable.
Disadvantages of Encapsulation
- Code Size: The length of the code increases drastically in the case of encapsulation as we need to provide all the methods with the specifiers.
- More Instructions: As the size of the code increases, therefore, you need to provide additional instructions for every method.
- Increased code execution: Encapsulation results in an increase in the duration of the program execution. It is because more instructions are added to the code therefore they require more time to execute.