Encapsulation in Java


Encapsulation is an object oriented programming concept that hides the personal data from outside world using the access specifiers; private and protected. Encapsulation basically means to protect the data in a class using private and protected. Data encapsulation is also called data hiding. Data hiding is where we do not want the user to have the access of the back end details or the details of the background of the program.

To bind the code with the data together in one single unit is called data encapsulation.

Encapsulation is also a concept of wrapping the code and the data together into a single unit.


Advantages of Encapsulation in Java:

Data encapsulation in Java programming language is useful as it provides control on the data. Through encapsulation real model entities are easy to make. It makes the classes easy to use. The code can be reused because of encapsulation.


Simple example of encapsulation in Java:

Consider the following example of encapsulation:

CODE:

package P {

public class Employee {

private String name;

public String get () {

return name;

}

public void set (String name) {

this. name = name;

}

}

package P {

class Testing {

public static void main (String args []) {

Employee z = new Employee ();

  1. set (“Stuart”);

system. out. println (z. get ());

}

}

OUTPUT:

Stuart

In the above example we used the concept of encapsulation and used the get () and set () methods to get the string name of the employee and set () method is used to set the value of the string type variable that is name. Then we printed the name that was passed to get () method by using the set () method.