Understanding Encapsulation and Access Modifiers
1. Using Access Modifiers
| Modifier | Class | Package | Subclass | World |
|---|---|---|---|---|
public | ✓ | ✓ | ✓ | ✓ |
protected | ✓ | ✓ | ✓ | ✗ |
| (default) | ✓ | ✓ | ✗ | ✗ |
private | ✓ | ✗ | ✗ | ✗ |
2. Creating Getter Methods
Example: Getters
public String getName() { return name; }
public boolean isActive() { return active; }
public List<Tag> getTags() { return List.copyOf(tags); } // defensive
| Convention | Pattern |
|---|---|
| Object/primitive | getName() |
| boolean | isActive() |
| Mutable field return | Return defensive copy or unmodifiable view |
3. Creating Setter Methods
| Practice | Detail |
|---|---|
| Naming | setName(String name) |
| Validation | Validate before assignment |
| Builder pattern | Return this for chaining |
| Avoid for immutables | Don't expose setters on immutable classes |
4. Understanding Package-Private Access
| Aspect | Detail |
|---|---|
| Modifier | None (no keyword) |
| Visible to | All classes in same package |
| Use case | Internal package collaboration |
5. Designing Immutable Classes
| Rule | Detail |
|---|---|
| Class | final (no subclassing) |
| Fields | private final |
| Constructor | Initialize all fields |
| Mutating methods | None — return new instance instead |
| Mutable fields | Defensive copy in/out |
| Modern | Use record when possible |
6. Understanding Information Hiding
| Principle | Application |
|---|---|
| Hide state | private fields |
| Expose behavior | public methods |
| Stable API | Internal changes don't break callers |
| Modules JAVA 9+ | exports only public API packages |
7. Using JavaBeans Conventions
| Requirement | Detail |
|---|---|
| Public no-arg constructor | Required |
| Properties | Accessed via getX/setX |
| Serializable | Implements java.io.Serializable |
| Used by | JSP, JSF, Spring, Jackson, JPA |
8. Working with Record Classes JAVA 16+
Example: Record
public record Point(int x, int y) {
// Compact constructor for validation
public Point {
if (x < 0 || y < 0) throw new IllegalArgumentException();
}
// Static factory
public static Point origin() { return new Point(0, 0); }
}
| Auto-generated | Detail |
|---|---|
| Constructor | Canonical with all components |
| Accessors | x(), y() (no get prefix) |
equals/hashCode/toString | Based on all components |
| Implicit modifiers | final class, final fields |
9. Understanding Record Components
| Aspect | Detail |
|---|---|
| Declaration | In header parentheses |
| Field | Auto-generated private final |
| Accessor | Same name as component |
| Reflection | getRecordComponents() |
| Annotations | Propagate to field, accessor, constructor param |
10. Comparing Records vs Traditional Classes
| Feature | Record | Class |
|---|---|---|
| Mutability | Immutable | Either |
| Inheritance | Cannot extend; can implement interfaces | Full |
| Boilerplate | Minimal | Manual |
| Use case | DTOs, value objects, tuples | General-purpose |
| Custom fields | Only static | Any |