Session 5: Access Modifiers, Encapsulation,
JavaBeans & Immutable Objects
1. Access Modifiers – The Four Guards of Java
Access modifiers control who can see and use your class members (variables & methods).
The four levels of access:
• private: Accessible only within the same class (like a safe inside your room).
• default: Accessible only within the same package (like neighbors in the same building).
• protected: Accessible within the same package and subclasses in other packages (like family
members).
• public: Accessible everywhere (like an open park).
2. Encapsulation – Data Hiding Mastery
Encapsulation means hiding internal details and exposing only what is necessary through public
methods.
Benefits:
• Hides data and implementation details.
• Protects the object state.
• Provides flexibility and maintainability.
3. JavaBean Standards – The Professional Way
A JavaBean is a reusable software component that follows naming conventions and standards.
Rules of a JavaBean:
• Private fields (data hiding).
• Public getters and setters for each property.
• A default no-argument constructor.
• Should be serializable (optional).
4. Immutable Objects – The Unbreakable Shield
Immutable objects cannot be changed after creation. Example: String in Java.
Rules for immutability:
• Declare the class as final.
• Make fields private and final.
• Do not provide setters.
• Initialize fields through constructor.
• Return copies of mutable fields instead of originals.
■ Summary
• Access Modifiers define visibility (private, default, protected, public).
• Encapsulation hides data and provides controlled access.
• JavaBeans follow getter/setter conventions for frameworks.
• Immutable Objects cannot change state once created.