Loading
Java Encapsulation-interview

Q1. What is encapsulation in Java?
Encapsulation is the process of wrapping data (variables) and methods that operate on that data into a single unit (class). It also involves restricting direct access to fields using private and providing controlled access using getters and setters.





Q2. Give a real-world example of encapsulation.
A bank account class where balance is private and can only be accessed/modified via deposit and withdraw methods ensures proper validation and prevents unauthorized modification.





Q3. How is encapsulation different from abstraction?
Encapsulation focuses on data hiding and access control, while abstraction focuses on hiding implementation details and showing only essential features.





Q4. How do you achieve encapsulation in Java?
    • Declare class variables as private.
    • Provide public getter and setter methods to access/modify data safely.






Q5. What are the advantages of encapsulation?
    • Data hiding prevents unauthorized access.
    • Flexibility we can add validation in setters.
    • Maintainability changes in class internals won’t affect external code.
    • Security sensitive data is protected.