group-icon
Java Developers
Group for Java developers and programmers. Ask questions and get answers related to Java programming
270 Members
Join this group to post and comment.
Archana Priyadarshini
Archana Priyadarshini
Computer Science
13 Feb 2019

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.

  1. Make members of a class as private.
  2. Define public setter and getter methods to modify and view the variables' values and access them outside the class only through getters and setters.

AdhikariHarika Reshma
AdhikariHarika Reshma
Computer Science
3mos ago

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.