Encapsulation in Java

uzairadamjee / February 13, 2018

Encapsulation is a technique in which you can bind your data and code together as a single unit. It’s a good approach to hide your data to make it safe from any modification.  The best way to understand encapsulation is to look at the example of a medical capsule, where the drug is always safe inside the capsule. Similarly, through encapsulation the methods and variables of a class are well hidden and safe.

Let us look at the code below to get a better understanding of encapsulation:


public class Student {

private String name;

public String getName() {
return name;
public void setName(String name) {
this.name = name;



In the above example I have created a Student class in which it has a private variable name. We have then created a getter and setter methods through which we can get and set the name of a student. So, any class which have to modify or access name variable has to use getter and setter methods.

Leave a Reply

Your email address will not be published.