Table of content

Encapsulation in Java

Encapsulation is the process of binding/encapsulating the data and code together.

Encapsulation is used to hide the implementation details. The encapsulation can be achieved by the use of 3 keywords in java.

private: The variables or methods that have been declared as private will not be accessible outside the class, But the same class member can access private methods and variables of the class.

protected : The variable or methods that have been declared as protected will be accessible inside the class in which they have been defined and in the classes which extend this class. Protected Getter and Protected setter can be used to give access to only their family members.

public : The variable or methods that have been declared as public will be accessible anywhere. Also, a class can be made public.

Mostly we use private and public methods for encapsulation. All the essential details which we do not want to disclose to other members will be part of the private method.

But somehow we want to let the user know the result of the private method, so we will create a public method in a way that the method will show only the result of the private method to the user but not the implementation of the private method.

In case if we want to give more access to the same family member, the inherited class then we create some protected methods which will provide more details of the private method result which outside members of the family cannot see.

In my Language : Consider an organization as a private method, employees as inherited class methods, General public or press as Outside members.

For every Quarter, the organization releases a newsletter stating the Profits/Losses to the press and employees, but the same organization gives details about which project made what profit to the employees through the internal newsletter.

In the below example, we allow the user to set and get the name of the employee using getter and setter, but we do not reveal any other details like how the name is processed and what are the operations happening to make up the emp name.

package newtest;
class EncapsulationExample {
 private String empName;

 private void modifyEmpName(String newName) {
  empName = newName + " : He acts in BigBang Theory";
 public String getEmpName() {
  return empName;
 public void setEmpName(String newName) {
public class EncapsulationTest {
 public static void main(String args[]) {
  EncapsulationExample obj = new EncapsulationExample();
  obj.setEmpName("Sheldon Cooper");


0 results
Comment / Suggestion Section
Point our Mistakes and Post Your Suggestions