Java — Encapsulation
Access modifiers
| Modifier | Class | Package | Subclass | World |
|---|---|---|---|---|
| public | ✓ | ✓ | ✓ | ✓ |
| protected | ✓ | ✓ | ✓ | ✗ |
| default | ✓ | ✓ | ✗ | ✗ |
| private | ✓ | ✗ | ✗ | ✗ |
Example
public class Person {
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Mini Practice
- Use private fields
- Create getters/setters
- Apply access modifiers
- Practice encapsulation
Up Next
Continue with Packages - Package organization.
Related Topics
Frequently Asked Questions about Encapsulation
What is Encapsulation in Java?
Encapsulation is a fundamental concept in Java. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Encapsulation?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Encapsulation.
Why is Encapsulation important in Java?
Encapsulation is essential for Java development. Understanding this concept will help you write better code and solve real-world problems more effectively.