Encapsulation

Encapsulation

In this tutorial, we will discuss encapsulation in Java. Encapsulation is one of the fundamentals of OOP (object-oriented programming). 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
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.

Encapsulation

Scroll to top