In this tutorial, we will discuss encapsulation in Java. Encapsulation is another key concept in object-oriented programming (OOP), closely related to abstraction. Encapsulation in Java is a process of wrapping code and data together into a single unit. For example, a capsule which is mixed with several medicines.ion is defined as the wrapping up of data ( under a single unit.

Encapsulation in Java

In Java, encapsulation is typically achieved by declaring the instance variables of a class as private and providing public getter and setter methods to access and modify those variables, respectively. This allows for better control over how the data is accessed and modified, enabling data validation, security, and easier maintenance.

How can we achieve Encapsulation?

By declaring the class’s member variables as private and providing public setter/getter methods to modify and view the variables’ values.

 * @author ashok.mariyala
public class Student {
   private String sid;
   private String sname;
   private String saddr;

   public String getSid() {
      return sid;

   public void setSid(String sid) {
      this.sid = sid;

   public String getSname() {
      return sname;

   public void setSname(String sname) {
      this.sname = sname;

   public String getSaddr() {
      return saddr;

   public void setSaddr(String saddr) {
      this.saddr = saddr;

Private member variables are only accessible within the class. Only by using the getter methods, the private members can be accessed outside the class.

Tightly Encapsulated Class

A class is said to be tightly encapsulated if and only if all the data members declared as private.

That’s all about Encapsulation in Java. If you have any queries or feedback, please write us at contact@waytoeasylearn.com. Enjoy learning, Enjoy Java.!!

Scroll to top