Encapsulation in Java

Encapsulation is a mechanism of binding code and data together in a single unit. Let’s take an example of Capsule. Different powdered or liquid medicines are encapsulated inside a capsule. Likewise in encapsulation, all the methods and variables are wrapped together in a single class.

Encapsulation In Java

We will see detailed explanation with some example programs about Encapsulation in the post related to Encapsulation.

Let’s see how can we implement encapsulation. Set the instance variables private so that these private variables cannot be accessed directly by other classes. Set getter and setter methods of the class as public so that we can set and get the values of the fields.

package encapsulationClass; public class EncapsulationClassOne { private int age; private String name; // getter method to access private variable public int getAge(){ return age; } public String getName(){ return name; } // setter method to access private variable public void setAge(int inputAge){ age = inputAge; } public void setName(String inputName){ name = inputName; } }

package encapsulationClass; public class EncapsulationClassTwo { public static void main(String [] args){ EncapsulationClassOne obj = new EncapsulationClassOne(); // Setting values of the variables obj.setAge(31); obj.setName("Pavi"); System.out.println("My name is "+ obj.getName()); System.out.println("My age is "+ obj.getAge()); } }

My name is Pavi My age is 31

In the above example, you can find all the data member (variables) are declared as private. If the data member is private it means it can only be accessed within the same class. No other class can access these private variables of other class. To access these private variables from other classes, we used public getter and setter methods such as getAge(), getName(), setAge(), setName(). So, the data can be accessed by public methods when we can set the variables private and hide their implementation from other classes. This way we call encapsulation as data hiding.

Advantage of Encapsulation in java

By providing only setter or getter method, you can make the class read-only or write-only.

It provides you the control over the data. Suppose you want to set the value of id i.e. greater than 100 only, you can write the logic inside the setter method.

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.

//save as Student.java package com.javatpoint; public class Student{ private String name; public String getName(){ return name; } public void setName(String name){ this.name=name } }

//save as Test.java package com.javatpoint; class Test{ public static void main(String[] args){ Student s=new Student(); s.setName("Rama"); System.out.println(s.getName()); } }

Compile By: javac -d . Test.java Run By: java com.javatpoint.Test Output: Rama