How to achieve encapsulation in Java?
The key advantage of using an Object Oriented Programming language like Java is that it provides your code - security, flexibility and its easy maintainability through encapsulation.
Encapsulation helps us in binding the data(instance variables) and the member functions(that work on the instance variables) of a class.
Encapsulation is also useful in hiding the data(instance variables) of a class from an illegal direct access.Encapsulation also helps us to make a flexible code which is easy to change and maintain.
Encapsulation in java is achieved by using private members and public methods.
- Make members of a class as private.
- Define public setter and getter methods to modify and view the variables' values and access them outside the class only through getters and setters.
Encapsulation in Java:It is a process of wrapping code and data together into a single unit.We can create a fully encapsulated class in java by making all the data members of the class private.Now we can use setter and getter methods t set and get the data in it.The Java bean class is the example of a fully encapsulated class.
Advantage of Encapsulation in Java:By providing only a getter or setter method we can make the class read only or write only.In other words we can skip the getter or setter methods.
It provides us the control over the data .suppose we want to set the value of id which should be greater than 100 only,we can write the logic inside the setter method.It is a way to achieve data hiding in java because other class will not be able t access the data through the private data members.The encapsulate class is easy to test,so it is better for unit testing and fast to create an encapsulated class in java.