Java Encapsulation
Java Encapsulation
In this tutorial, you will learn about encapsulation and data hiding in Java with
the help of examples.
Java Encapsulation
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.
class Main {
public static void main(String[] args) {
Output
Area: 30
In the above example, we have created a class named Area . The main
purpose of this class is to calculate the area.
To calculate an area, we need two variables: length and breadth and a
method: getArea() . Hence, we bundled these fields and methods inside a single
class.
Here, the fields and methods can be accessed from other classes as well.
Hence, this is not data hiding.
This is only encapsulation. We are just keeping similar codes together.
Note: People often consider encapsulation as data hiding, but that's not
entirely true.
Encapsulation refers to the bundling of related fields and methods together.
This can be used to achieve data hiding. Encapsulation in itself is not data
hiding.
Why Encapsulation?
In Java, encapsulation helps us to keep related fields and methods
together, which makes our code cleaner and easy to read.
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.
The getter and setter methods provide read-only or write-only access
to our class fields. For example,
And, they are kept hidden from outer classes. This is called data
hiding.
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.
// private field
private int age;
// getter method
public int getAge() {
return age;
}
// setter method
public void setAge(int age) {
this.age = age;
}
}
class Main {
public static void main(String[] args) {
// create an object of Person
Person p1 = new Person();
Output
My age is 24
In 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() .
REFERENCES: https://www.programiz.com/java-programming/encapsulation