Encapsulation

Encapsulation

 If a class follows data hiding and abstraction such type of class is said to be β€˜Encapsulated’ class.

Encapsulation = Data Hiding + Abstraction
/**
 * 
 * @author ashok.mariyala
 *
 */
public class Employee {
   private String empName;
   private String empId;
   private String empAddress;
   private double salary;

   public String getEmpName() {
      return empName;
   }

   public void setEmpName(String empName) {
      this.empName = empName;
   }

   public String getEmpId() {
      return empId;
   }

   public void setEmpId(String empId) {
      this.empId = empId;
   }

   public String getEmpAddress() {
      return empAddress;
   }

   public void setEmpAddress(String empAddress) {
      this.empAddress = empAddress;
   }

   public double getSalary() {
      return salary;
   }

   public void setSalary(double salary) {
      this.salary = salary;
   }

   @Override
   public String toString() {
      return "Employee [empName=" + empName + ", empId=" + empId + ", empAddress=" + empAddress + ", salary=" + salary
            + "]";
   }
}

The data members we have to declared as private. So that outside person is not allowed to access to directly we have to provide Access to our data by defining setter and getter methods. i.e hiding data behind methods is the central concept of encapsulation.

The main advantages of encapsulation are security, enhancement, maintainability

Tightly Encapsulated Class

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

/**
 * 
 * @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;
   }
}

Encapsulation


Scroll to top