Java Encapsulation and its Uses With examples

In this tutorial we will see the Java Encapslation, its uses along with some examples. Encapsulation is a mechanism through which we can protect the data (data members) of our class from being directly accessed by some other code outside the class.

Consider you have a Employee class, in which you have some data members(empName, empId, empSalary, empAge etc). So you can create as many object as you want and assign the values to those data members. But think about this scenario, you have employee class and you feel that all employees must be above 18 years of age and no one should be below 18. So how we going to handle this.?

The solution is “Encapsulation“, so using encapsulation we can validate before writing the value into our data member.

Lets see with some Example:

Employee.java

package blocks;

public class Employee {
    private String empId;
    private String empName;
    private int empAge;
    private String empDesignation;
    private double basic;
    private double HRA;
    
    public Employee(String empId,String empName, int empAge, String empDesignation, double basic,double hRA){
        if(empAge>18){
            this.empId = empId;
            this.empName = empName;
            this.empAge = empAge;
            this.empDesignation = empDesignation;
            this.basic = basic;
            this.HRA = HRA;
        }
    }
    public String getEmpId() {
        return empId;
    }
    public void setEmpId(String empId) {
        this.empId = empId;
    }
    public String getEmpName() {
        return empName;
    }
    public void setEmpName(String empName) {
        this.empName = empName;
    }
    public int getEmpAge() {
        return empAge;
    }
    public void setEmpAge(int empAge) {
        this.empAge = empAge;
    }
    public String getEmpDesignation() {
        return empDesignation;
    }
    public void setEmpDesignation(String empDesignation) {
        this.empDesignation = empDesignation;
    }
    public double getBasic() {
        return basic;
    }
    public void setBasic(double basic) {
        this.basic = basic;
    }
    public double getHRA() {
        return HRA;
    }
    public void setHRA(double hRA) {
        HRA = hRA;
    }
    @Override
    public String toString() {
        // TODO Auto-generated method stub
        return getEmpId() +"-"+getEmpName()+"-"+getEmpAge()+"-"+getEmpDesignation()+"-"+getHRA()+"-"+getBasic();
    }
}

EmployeeImpl.java

package blocks;

public class EmployeeImpl {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
            Employee employeeOne = new Employee("1","Sree",20,"Manager",2345,454);
            Employee employeeTwo = new Employee("1","Dharan",18,"Supervisor",2000,454);
            Employee employeeThree = new Employee("1","Arun",23,"Supervisor",2000,454);
            System.out.println(employeeOne);
            System.out.println(employeeTwo);
            System.out.println(employeeThree);
    }

}

Output will be

1-Sree-20-Manager-0.0-2345.0
null-null-0-null-0.0-0.0
1-Arun-23-Supervisor-0.0-2000.0

If you notice the output for employeeOne and employeeThree it’s printing the values but for employeeTwo its printing null. Even though we initialized the object, based on some conditions only we are assigning the values. In the above example we set the values using constructor, also we can also set the values using the setter method (setEmpName,setEmpId etc).

We have seen writing the values to the data member in Employee class, now imagine in the Employee Class we have empBasic and empHRA and any anyone can able to see your salary outside this class. So in order to prevent that we made the variable as private, and have a public getter methods. So those who have access can able to see the salary. Another real time examples is in our facebook profile. We can hide our photos to public members, so that only our friends can see our photos. Even in FB we can hide our date of birth, mobile number etc. These are all some real time examples.

Another main advantage of this encapsulation is, it will provide implementation details by extending the code. For example consider you want to create a salary of Employee by calculating basic and hra based on some logic as mentioned below.

package blocks;

import java.util.ArrayList;
import java.util.List;

public class EmployeeImpl {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
            Employee employeeOne = new Employee("1","Sree",20,"Manager",2345,454);
            Employee employeeThree = new Employee("1","Arun",23,"Supervisor",2000,454);
            List<Employee> empList = new ArrayList<>();
            empList.add(employeeOne);
            empList.add(employeeThree);
            for(Employee employee :empList){
                if(employee.getEmpDesignation().equals("Manager")){
                    System.out.println( "Salary of a "+employee.getEmpDesignation() +" is : "+1000+ employee.getHRA()+employee.getBasic());
                }else{
                    System.out.println( "Salary of a "+employee.getEmpDesignation() +" is : "+500+ employee.getHRA()+employee.getBasic());
                }
            }
    }
}

Output will be

Salary of a Manageris : 10000.02345.0
Salary of a Supervisoris : 5000.02000.0

If you see the EmployeeImpl.java for each object we used its corresponding getter methods to get the HRA and Basic value and do the salary calculation. So instead of this we can directly move this implementation to Employee class with calculateSalary() method, so that we need not call all the getter methods and do the manipulation

Employee.java

package blocks;

public class Employee {
    private String empId;
    private String empName;
    private int empAge;
    private String empDesignation;
    private double basic;
    private double HRA;
    
    public Employee(String empId,String empName, int empAge, String empDesignation, double basic,double hRA){
        if(empAge>18){
            this.empId = empId;
            this.empName = empName;
            this.empAge = empAge;
            this.empDesignation = empDesignation;
            this.basic = basic;
            this.HRA = HRA;
        }
    }
    public String getEmpId() {
        return empId;
    }
    public void setEmpId(String empId) {
        this.empId = empId;
    }
    public String getEmpName() {
        return empName;
    }
    public void setEmpName(String empName) {
        this.empName = empName;
    }
    public int getEmpAge() {
        return empAge;
    }
    public void setEmpAge(int empAge) {
        this.empAge = empAge;
    }
    public String getEmpDesignation() {
        return empDesignation;
    }
    public void setEmpDesignation(String empDesignation) {
        this.empDesignation = empDesignation;
    }
    public double getBasic() {
        return basic;
    }
    public void setBasic(double basic) {
        this.basic = basic;
    }
    public double getHRA() {
        return HRA;
    }
    public void setHRA(double hRA) {
        HRA = hRA;
    }
    @Override
    public String toString() {
        // TODO Auto-generated method stub
        return getEmpId() +"-"+getEmpName()+"-"+getEmpAge()+"-"+getEmpDesignation()+"-"+getHRA()+"-"+getBasic();
    }
    
    public double calculateSalary(){
        if(empDesignation.equalsIgnoreCase("Manager")){
             return 1000+ HRA + basic;
        }else{
            return 500+ HRA + basic;
        }
    }
}

EmployeeImpl.java

package blocks;

import java.util.ArrayList;
import java.util.List;

public class EmployeeImpl {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
            Employee employeeOne = new Employee("1","Sree",20,"Manager",2345,454);
            Employee employeeThree = new Employee("1","Arun",23,"Supervisor",2000,454);
            List<Employee> empList = new ArrayList<>();
            empList.add(employeeOne);
            empList.add(employeeThree);
            for(Employee employee :empList){
                System.out.println(employee.calculateSalary());
            }
    }
}

Output will be

3345.0
2500.0

So apart from protective barrier, encapsulation also help in extensibility, maintainability and flexibility of a code.

2 thoughts on “Java Encapsulation and its Uses With examples

  1. thanks for updates..in this site letters font is looks different and attract to reading….easy to learn for me..

Leave a comment

Your email address will not be published. Required fields are marked *