Description
Encapsulation is a fundamental OOP principle that bundles data (fields) and methods (behaviors) together in a class, while hiding internal implementation details from outside access. It’s achieved through access modifiers and getter/setter methods.
Key Concepts
What is Encapsulation?
- Bundling: Data and methods that operate on that data are grouped together
- Data hiding: Internal state is hidden from direct external access
- Access control: Use access modifiers to control visibility
- Controlled access: Provide controlled access through public methods
Access Modifiers
- private: Only accessible within the same class
- default (package-private): Accessible within the same package
- protected: Accessible within the same package and subclasses
- public: Accessible from anywhere
Benefits
- Data protection: Prevent unauthorized access and modification
- Validation: Validate data before setting (in setters)
- Flexibility: Change internal implementation without affecting clients
- Maintainability: Centralize data access logic
- Security: Control how data is accessed and modified
Getter and Setter Pattern
- Getters: Methods to read private field values
- Setters: Methods to modify private field values with validation
- Follow naming convention:
getFieldName() and setFieldName(value) - For boolean fields, use
isFieldName() instead of getFieldName()
When to Use
- Always make fields private unless there’s a good reason
- Use getters/setters for controlled access
- Validate inputs in setters
- Use final for immutable fields
- Consider making classes immutable when possible
Best Practices
- Make fields private by default
- Provide getters for fields that need to be read
- Provide setters only when fields need to be modified
- Add validation in setters
- Use meaningful method names
- Consider builder pattern for complex objects
- Use final to prevent modification of references
Common Patterns
- Immutable objects: No setters, all fields final
- Builder pattern: Construct objects with validation
- Read-only properties: Only getters, no setters
- Lazy initialization: Initialize fields on first access
Comments
No comments yet. Be the first!
Please login to leave a comment.