Encapsulation
- Keshari Abeysinghe

- Mar 20, 2020
- 2 min read
Updated: Nov 30, 2020
Encapsulation is one of the key features of object-oriented programming. Encapsulation refers to the bundling of fields and methods inside a single class.
It prevents outer classes from accessing and changing fields and methods of a class. This also helps to achieve data hiding.
Why use Encapsulation?
The getter and setter methods provide read-only or write-only access to our class fields. For example,
getName() // provides read-only access
setName() // provides write-only accessIn Java, encapsulation helps us to keep related fields and methods together, which makes our code cleaner and easy to read.
It helps to control the values of our data fields. For example,
class Person {
private int age;
public void setAge(int age) {
if (age >= 0) {
this.age = age;
}
}
}Here, we are making the age variable private and applying logic inside the setAge() method. Now, age cannot be negative.
It helps to decouple components of a system. For example, we can encapsulate code into multiple bundles. These decoupled components (bundle) can be developed, tested, and debugged independently and concurrently. And, any changes in a particular component do not have any effect on other components.
We can also achieve data hiding using encapsulation. In the above example, if we change the length and breadth variable into private, then the access to these fields is restricted.They are kept hidden from outer classes. This is called data hiding.Data hiding is a way of restricting the access of our data members by hiding the implementation details. Encapsulation also provides a way for data hiding. We can use access modifiers to achieve data hiding.
For example
class Student {
private int age;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
class School {
public static void main(String[] args) {
Student stu= new Student();
stu.setAge(24);
System.out.println("My age is " + stu.getAge());
}
}
Expected output
My age is 24In the above example, we have a private field age. Since it is private, it cannot be accessed from outside the class.
In order to access age, we have used public methods: getAge() and setAge(). These methods are called getter and setter methods.
Making age private allowed us to restrict unauthorized access from outside the class. This is data hiding.
Happy Coding!
Comments