Encapsulation in Java
Is it use for data hiding? Yes it is Encapsulation is data hiding. But what is the point of hiding data.
- Encapsulation limits the access for data.
Some cases we need to provide read only access for that we use encapsulation. Let’s take an example — For a student, student id should not be able to change after it assigned as follows. Then we have to make that variable private and make a method to read it. Then it cannot be changed.
public class Students { private String name;
private String address;
private String id; Student(String name, String address, String id) {
this.name = name;
this.address = address;
this.id = id;
}
public String getName() {
return this.name;
} public void setName(String name) {
this.name = name;
} public String getAddress() {
return this.address;
} public void setAddress(String address) {
this.address = address;
} public String getId() {
return this.id;
}
}
Should we need to use get word as a prefix to get data? No. But it is a good practice.
- Encapsulation helps to logically access the data.
In some cases we have to set limits or set the variables according to some conditions then we can use encapsulation to provide method to modify the variable as follows.
public void setMarks(int marks) throws SomeException{
if (marks <= 100 && marks >= 0) {
this.marks = marks
} else {
throw new SomeException("error");
}
Hopefully this is helpful.
If you have found this helpful please hit that 👏 and share it on social media :).