Java
Encapsulation
Hide internal data.
Encapsulation is one of the four pillars
of Object-Oriented Programming (OOP),
often described as Data Hiding + Bundling.
Encapsulation as a Casio
The point of Encapsulation is to hide
In life we often need to learn how to.
encapsulate our personal information.
Not only in the online world,
but also along people we know.
Privacy is power. People cannot ruin what they don't know.
The same happens in our application.
The more secure and private our data,
the more control we have.
Classes expose only certain fields and methods
to other classes for access.
How to encapsulate in Java OCA Exam
- Declare all instance variables (data) as
private. - Provide
publicmethods, commonly called Getters (access/read) and Setters (modify/write), to manage access to the private variables.
public class Student {
private String name;
private int age;
// Getter method for name
public String getName() {
return name;
}
// Setter method for name
public void setName(String name) {
this.name = name;
}
// Getter method for age
public int getAge() {
return age;
}
// Setter method for age
public void setAge(int age) {
if (age > 0) {
this.age = age;
}
}
}Beware of protected
The "protected does not mean encapsulated" .violate strict encapsulation.
Key Benefits
- Data Integrity/Validation: Setters allow you to enforce rules (e.g., age cannot be negative) before modifying the data.
- Control: You can make a variable read-only (provide a Getter but no Setter) or write-only.
- Flexibility/Decoupling: You can change the internal data structure or implementation (e.g., rename a private variable) without breaking any external code that relies only on the public methods.
🦕 Sources
- Oracle Java Documentation: Encapsulation
- Baeldung: Encapsulation in Java
- GeeksforGeeks: Encapsulation in Java