Java Encapsulation with Getters and Setters – Complete Guide with Examples
Learn Java encapsulation, how to hide data using private fields, and control access with getters and setters for secure, maintainable, and modular object-oriented programming.
Encapsulation and Getters/Setters in Java – Complete Detailed Tutorial
Encapsulation is one of the core OOP concepts in Java.
It is the technique of wrapping data (variables) and code (methods) together in a single unit (class) and restricting direct access to data from outside the class.
1. Why Encapsulation is Important
- Data Hiding: Protects variables from unauthorized access
- Controlled Access: Access only through methods
- Improved Security: Sensitive data like passwords are safe
- Code Maintainability: Changes to variables can be managed easily
- Better Modularity: Methods act as the interface to data
2. How to Implement Encapsulation
- Declare variables as private
- Provide public getter and setter methods to access and modify private data
Syntax:
3. Example – Encapsulation
Output:
4. Advantages of Using Getters and Setters
- Control Access: Can add validation before setting values
- Read-Only or Write-Only: Provide only getter or only setter
- Encapsulated Data: Reduces risk of unintended modification
- Flexible Maintenance: Modify internal implementation without affecting users
5. Example – Read-Only and Write-Only Fields
Output:
6. Best Practices for Encapsulation
- Keep fields private
- Provide public getters and setters
- Add validation in setters
- Use read-only or write-only access as needed
- Follow consistent naming conventions (
getVariable,setVariable)
7. Summary
- Encapsulation → wrapping variables and methods together, restricting direct access
- Getters and Setters → public methods to access private variables
- Advantages: data hiding, validation, maintainability, security, modularity