Understanding Encapsulation and Access Modifiers

1. Using Access Modifiers

ModifierClassPackageSubclassWorld
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
ConventionPattern
Object/primitivegetName()
booleanisActive()
Mutable field returnReturn defensive copy or unmodifiable view

3. Creating Setter Methods

PracticeDetail
NamingsetName(String name)
ValidationValidate before assignment
Builder patternReturn this for chaining
Avoid for immutablesDon't expose setters on immutable classes

4. Understanding Package-Private Access

AspectDetail
ModifierNone (no keyword)
Visible toAll classes in same package
Use caseInternal package collaboration

5. Designing Immutable Classes

RuleDetail
Classfinal (no subclassing)
Fieldsprivate final
ConstructorInitialize all fields
Mutating methodsNone — return new instance instead
Mutable fieldsDefensive copy in/out
ModernUse record when possible

6. Understanding Information Hiding

PrincipleApplication
Hide stateprivate fields
Expose behaviorpublic methods
Stable APIInternal changes don't break callers
Modules JAVA 9+exports only public API packages

7. Using JavaBeans Conventions

RequirementDetail
Public no-arg constructorRequired
PropertiesAccessed via getX/setX
SerializableImplements java.io.Serializable
Used byJSP, 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-generatedDetail
ConstructorCanonical with all components
Accessorsx(), y() (no get prefix)
equals/hashCode/toStringBased on all components
Implicit modifiersfinal class, final fields

9. Understanding Record Components

AspectDetail
DeclarationIn header parentheses
FieldAuto-generated private final
AccessorSame name as component
ReflectiongetRecordComponents()
AnnotationsPropagate to field, accessor, constructor param

10. Comparing Records vs Traditional Classes

FeatureRecordClass
MutabilityImmutableEither
InheritanceCannot extend; can implement interfacesFull
BoilerplateMinimalManual
Use caseDTOs, value objects, tuplesGeneral-purpose
Custom fieldsOnly staticAny