Description
Encapsulation is the mechanism of wrapping data (variables) and methods that operate on the data into a single unit, i.e., a class.
- It hides the internal implementation details of an object from the outside world.
- Access to data is provided through getter and setter methods, controlling how variables are accessed or modified.
- This concept supports data hiding and helps to protect the integrity of the object’s state.
Encapsulation improves modularity, prevents unauthorized access, and promotes a clean and maintainable codebase.
Video Resources
Java Encapsulation Explained
Clear explanation of encapsulation with code examples in Java.
Encapsulation in Java with Examples
Demonstrates how to implement encapsulation and data hiding in Java.
Examples (code)
Encapsulation Example
// Class with encapsulation
class Person {
private String name; // private variable
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 with validation
public void setAge(int age) {
if (age > 0) {
this.age = age;
}
}
}
public class Main {
public static void main(String[] args) {
Person person = new Person();
person.setName("Basha Ram");
person.setAge(21);
System.out.println("Name: " + person.getName());
System.out.println("Age: " + person.getAge());
}
}
Real-World Applications
Data Protection
Encapsulation protects sensitive data by restricting direct access and exposing only necessary parts through methods.
Improved Maintainability
Changing internal implementation is easier without affecting external code using encapsulation.
Secure Code Design
Encapsulation helps design secure and robust applications by controlling data access.
Interview Questions
Q1: What is encapsulation in Java?
Encapsulation is the practice of wrapping data and methods into a single unit (class) and restricting access to some components using access modifiers.
Q2: How does encapsulation help in data hiding?
By declaring variables private and providing public getter and setter methods, encapsulation hides the internal state and protects it from unauthorized access or modification.
Q3: Can encapsulation be achieved without getter and setter methods?
Getter and setter methods are the common way to achieve encapsulation, but access can also be controlled using access modifiers and other design techniques.