Encapsulation is not meant for data hiding

Rony Emrul
2 min readOct 23, 2020

--

While defining encapsulation many will refer that encapsulation is,

  1. Wrapping the data and the functionality and representing it as a single entity
  2. Hiding the data members to achieve security

Well, although for encapsulation no. 1 is true the no. 2 is not always true.
Let’s see why.

Employee.java

public class Employee{private String name;private int age;private String designation;private EmployeeAddress employeeAddress = new EmployeeAddress();public Employee(String name, int age, String designationn){this.name = name;this.age = age;this.designation = designationn;
}
....
....
// getter and setters
....
....
}

EmployeeAddress.java

public class EmployeeAddress{private String city;private String area;private int postalCode;
...
...
// getter and setters
...
...
}

Test.java

public class Test{public static void main(String[] args) {Employee employee = new Employee("Ross", 30, "Paleontologist");EmployeeAddress employeeAddress = employee.getEmployeeAddress();employeeAddress.setCity("Dhaka");employeeAddress.setArea("Dhanmondi");employeeAddress.setPostalCode(1209);System.out.println(employee.toString());}}

Output:

Employee [age=30, designation=Paleontologist, name=Ross, employeeAddress=EmployeeAddress [area=Dhanmondi, city=Dhaka, postalCode=1209]]

As we can see that we can manipulate the EmployeeAddress without calling the setter method on the EmployeeAddress object. Although Employee class is encapsulated we can still change EmployeeAddress object without calling the setter method on it. So EmployeeAddress is not effectively hidden here.

So, why Encapsulation then?

  1. It gives better re-usability, flexibility and maintainability
    If we change a field of Employee class field other classes will not have a side effect. As they access the field through getter and setter methods.
  2. It gives abstraction
    Let’s say we want to validate the field age. So, we need to implement validation logic inside setAge() method. The user doesn’t need to know the validation logic. He’ll just pass the value.
public void setAge(int age){
if (age > 30){
throw new IllegalArgumentException("Age can't be greater than 30");
}
this.age = age;
}

3. We can achieve read/write only mode
We can make a field read-only by providing only a getter() method to it. Or, we can make it write-only by providing only the setter() method to it.

--

--

Rony Emrul

Backend Software Engineer, Technology Enthusiast