Encapsulation
2 min readNov 23, 2024
What is Encapsulation?
- Bundling data and methods into a single unit, and hiding the data from other classes.
- It restricts direct access to some of an object’s components and can prevent the accidental modification of data.
Key Concepts
- Data Hiding:
- Encapsulation allows the internal state of an object to be hidden from the outside. This means that the data of a class can only be accessed through methods (getters and setters).
- This protects the integrity of the data and prevents unauthorized access.
2. Access Modifiers:
- Java provides access modifiers to set the visibility of classes, methods, and variables:
- private: The member is accessible only within its own class.
- public: The member is accessible from any other class.
- protected: The member is accessible within its own package and by subclasses.
- default (no modifier): The member is accessible only within its own package.
Get Harshh🎀’s stories in your inbox
Join Medium for free to get updates from this writer.
3. Getters and Setters:
- Getters are methods that retrieve the value of a private variable.
- Setters are methods that set or update the value of a private variable.
- Using getters and setters allows you to control how variables are accessed and modified.
public class Person {
// Private variables (data hiding)
private String name;
private int age;
// Constructor
public Person(String name, int age) {
this.name = name;
this.age = age;
}
// Getter for name
public String getName() {
return name;
}
// Setter for name
public void setName(String name) {
this.name = name;
}
// Getter for age
public int getAge() {
return age;
}
// Setter for age
public void setAge(int age) {
if (age > 0) { // Example of validation
this.age = age;
} else {
System.out.println("Age must be positive.");
}
}
}






