Encapsulation in Object Oriented Programming (OOPs) MCQ Questions and Answers
1. Which of the following best describes encapsulation in object-oriented programming?
A) Exposing all fields of a class for easy access
B) Combining data and methods that operate on that data into a single unit and restricting access to some of the object’s components
C) Inheriting behaviour from multiple parent classes
D) Writing only static methods in a class
Answer: B) Combining data and methods that operate on that data into a single unit and restricting access to some of the object’s components
2. Which mechanism is primarily used to enforce encapsulation in most object-oriented languages?
A) Polymorphism
B) Access modifiers (e.g., private, protected, public)
C) Dynamic typing
D) Garbage collection
Answer: B) Access modifiers (e.g., private, protected, public)
3. What is information hiding in the context of encapsulation?
A) Hiding the source code from the compiler
B) Hiding internal object representation and exposing only necessary interfaces
C) Encrypting data before storing it
D) Using macros to hide implementation
Answer: B) Hiding internal object representation and exposing only necessary interfaces
4. Which of these is a direct benefit of encapsulation?
A) Increased coupling between modules
B) Easier maintenance and controlled modification of internal state
C) Unlimited access to object internals from anywhere
D) Faster compilation time
Answer: B) Easier maintenance and controlled modification of internal state
5. In Java, which access modifier makes a class member visible only within its own class?
A) public
B) protected
C) private
D) default (package-private)
Answer: C) private
6. Which statement about getters and setters is true?
A) They are unrelated to encapsulation
B) They provide controlled access to private fields and can enforce validation
C) They always break encapsulation
D) They are only used for static variables
Answer: B) They provide controlled access to private fields and can enforce validation
7. Which of the following would most likely violate encapsulation?
A) Using private fields with public getters and setters
B) Using final fields for immutable state
C) Making all fields public so other classes modify them directly
D) Exposing only an interface while hiding implementation classes
Answer: C) Making all fields public so other classes modify them directly
8. In C++, which feature allows friend functions to access private members and therefore partially break encapsulation?
A) Templates
B) Virtual functions
C) friend keyword
D) Namespaces
Answer: C) friend keyword
9. Which principle suggests that a class should expose as little as possible of its internal representation?
A) Polymorphism principle
B) Don’t Repeat Yourself (DRY)
C) Principle of least privilege / information hiding
D) Open/Closed Principle
Answer: C) Principle of least privilege / information hiding
10. What does immutability have to do with encapsulation?
A) Immutability makes encapsulation unnecessary
B) Immutability is enforced by public fields
C) Immutable objects expose no mutating operations, which complements encapsulation by protecting internal state
D) Immutability requires making all fields protected
Answer: C) Immutable objects expose no mutating operations, which complements encapsulation by protecting internal state
11. Which of the following code patterns is most encapsulation-friendly?
A) class C { public: int x; }
B) class C { private: int x; public: int getX(); void setX(int v); }
C) class C { protected: int x; }
D) struct C { int x; };
Answer: B) class C { private: int x; public: int getX(); void setX(int v); }
12. Which OOP concept is distinct from but closely related to encapsulation?
A) Abstraction
B) Assembly linking
C) Procedural programming
D) Preprocessor directives
Answer: A) Abstraction
13. Which is an example of breaking encapsulation intentionally for testing or serialization?
A) Making fields private and providing no accessors
B) Using reflection to access private fields
C) Using public getters only
D) Using immutable value objects
Answer: B) Using reflection to access private fields
14. In Java, which modifier allows access to a member from classes in the same package but not from outside packages?
A) public
B) default (no modifier)
C) private
D) final
Answer: B) default (no modifier)
15. Which design pattern helps preserve encapsulation by providing a simplified interface to a complex subsystem?
A) Observer
B) Strategy
C) Facade
D) Singleton
Answer: C) Facade
16. In the context of encapsulation, why might you prefer methods over direct field access?
A) Methods are slower so they discourage use
B) Methods allow input validation, lazy computation, or logging before exposing internal data
C) Methods always use more memory
D) Methods make serialization impossible
Answer: B) Methods allow input validation, lazy computation, or logging before exposing internal data
17. Which of the following statements about properties (as in C#) is true regarding encapsulation?
A) Properties expose internal fields publicly with no control
B) Properties provide a syntactic way to use getters and setters, maintaining encapsulation while giving field-like access
C) Properties are only for static members
D) Properties break encapsulation by default
Answer: B) Properties provide a syntactic way to use getters and setters, maintaining encapsulation while giving field-like access
18. Which access modifier in C# allows access to a member only within its declaring class?
A) internal
B) protected
C) private
D) public
Answer: C) private
19. Which of the following is NOT a reason to encapsulate fields behind getters and setters?
A) Perform validation when setting values
B) Maintain invariants of the object
C) Allow future change of internal representation without changing API
D) Guarantee that every field is accessible from anywhere in code
Answer: D) Guarantee that every field is accessible from anywhere in code
20. Which of the following best describes “tight coupling” in relation to encapsulation?
A) Tight coupling means classes are independent and encapsulated properly
B) Tight coupling results from exposing internal details and leads to poor encapsulation
C) Tight coupling is beneficial for encapsulation
D) Tight coupling enforces immutability
Answer: B) Tight coupling results from exposing internal details and leads to poor encapsulation
21. Consider a class with a private list field. Which approach maintains encapsulation when providing access to the list?
A) Return the private list directly
B) Return a shallow copy or an unmodifiable/read-only view of the list
C) Make the list public
D) Use global variables instead
Answer: B) Return a shallow copy or an unmodifiable/read-only view of the list
22. Which of these Java statements best hides an implementation detail?
A) public ArrayList getList() { return list; }
B) public List getList() { return Collections.unmodifiableList(list); }
C) public int[] getArray() { return internalArray; }
D) public int internalValue;
Answer: B) public List getList() { return Collections.unmodifiableList(list); }
23. When is it acceptable to use public fields (no encapsulation) in production code?
A) For mutable shared resources accessed concurrently
B) Rarely; sometimes for simple, immutable constants (static final) or POD-like data structures where encapsulation adds no benefit
C) Always; encapsulation is unnecessary
D) For security-sensitive data
Answer: B) Rarely; sometimes for simple, immutable constants (static final) or POD-like data structures where encapsulation adds no benefit
24. Which technique helps enforce encapsulation at compile time in statically-typed languages?
A) run-time reflection
B) using access modifiers (private/protected) and final/const qualifiers
C) dynamic imports
D) code comments
Answer: B) using access modifiers (private/protected) and final/const qualifiers
25. If a class exposes a setter that can set an invalid state, which principle is being violated?
A) Open/Closed Principle
B) Encapsulation / class invariant enforcement
C) Single Responsibility Principle
D) Liskov Substitution Principle
Answer: B) Encapsulation / class invariant enforcement
26. Which is a correct statement about protected members?
A) Protected members are accessible only within the same class instance
B) Protected members are accessible from unrelated classes in other packages by default
C) Protected members are accessible within the same class, subclasses, and package (language-dependent specifics apply)
D) Protected is identical to private
Answer: C) Protected members are accessible within the same class, subclasses, and package (language-dependent specifics apply)
27. Which of the following is a valid encapsulation strategy for thread-safe state?
A) Expose mutable fields publicly and synchronize callers
B) Use private fields and provide synchronized accessors / immutable snapshots instead
C) Make all fields volatile and public
D) Never use synchronization; rely on caller discipline
Answer: B) Use private fields and provide synchronized accessors / immutable snapshots instead
28. In languages that support reflection (e.g., Java, C#), what is a common risk to encapsulation?
A) Reflection enforces encapsulation strictly
B) Reflection can be used to access and modify private fields, bypassing access controls
C) Reflection makes programs run faster
D) Reflection prevents serialization
Answer: B) Reflection can be used to access and modify private fields, bypassing access controls
29. Which approach best supports API evolution while preserving encapsulation?
A) Returning concrete types and exposing internal classes
B) Returning interfaces or abstract types instead of concrete implementations
C) Making fields public for convenience
D) Using global mutable state for data sharing
Answer: B) Returning interfaces or abstract types instead of concrete implementations
30. Which of the following statements about encapsulation and testing is true?
A) Encapsulation makes unit testing impossible
B) Encapsulation requires that tests access private members directly
C) Encapsulation encourages testing behavior via public interfaces rather than internal state
D) Encapsulation removes the need for tests
Answer: C) Encapsulation encourages testing behavior via public interfaces rather than internal state
31. Consider a class with a private integer field age. Which setter enforces encapsulation best?
A) public void setAge(int a) { age = a; }
B) public void setAge(int a) { if (a >= 0) age = a; }
C) public int age;
D) public void setAge(int a) { age = a; } // no checks
Answer: B) public void setAge(int a) { if (a >= 0) age = a; }
32. Which of the following most weakens encapsulation in a large codebase?
A) Replacing fields with accessor methods
B) Documenting invariants in comments only and relying on everyone to follow them
C) Returning defensive copies when necessary
D) Using interfaces to hide implementation
Answer: B) Documenting invariants in comments only and relying on everyone to follow them
33. In languages with package-level access, what is a tradeoff of using package-private members for encapsulation?
A) Stronger cross-package hiding
B) Members are hidden from outside the package but accessible within the package, which may expose internals to unrelated classes inside the package
C) It prevents unit tests from accessing internals
D) It makes members public across all packages
Answer: B) Members are hidden from outside the package but accessible within the package, which may expose internals to unrelated classes inside the package
34. Which of the following statements is true for data encapsulation in procedural vs OOP languages?
A) Procedural languages cannot encapsulate any data
B) OOP languages provide structured mechanisms (classes, modifiers) for encapsulation; procedural code may need conventions or modules to achieve similar effects
C) Encapsulation is only useful in procedural languages
D) Encapsulation in OOP requires global variables
Answer: B) OOP languages provide structured mechanisms (classes, modifiers) for encapsulation; procedural code may need conventions or modules to achieve similar effects
35. What is the potential downside of providing getters for every private field?
A) No downside — always recommended
B) It may leak implementation details and create a maintenance burden by exposing unnecessary internal state
C) It improves encapsulation always
D) It prevents polymorphism
Answer: B) It may leak implementation details and create a maintenance burden by exposing unnecessary internal state
36. When designing a class, what is a good heuristic to decide whether to expose a field via a getter?
A) Expose all internal fields by default for flexibility
B) Expose only what clients need; prefer behavior-oriented methods over exposing raw data
C) Never expose any data, even if needed
D) Expose fields only as public for performance
Answer: B) Expose only what clients need; prefer behavior-oriented methods over exposing raw data
37. Which language feature helps create truly immutable objects (helps encapsulation)?
A) public mutable fields
B) final/const fields set only during construction and no mutating methods
C) Reflection-based field modification allowed
D) Exposing internal arrays directly
Answer: B) final/const fields set only during construction and no mutating methods
38. Which of the following best defines defensive copying in encapsulation?
A) Copying source code to another file
B) Returning internal mutable objects as copies to prevent callers from modifying internal state
C) Using copy constructors only in testing
D) Serializing objects to strings
Answer: B) Returning internal mutable objects as copies to prevent callers from modifying internal state
39. Which access level allows subclass access but hides the member from the rest of the codebase (language dependent)?
A) public
B) private
C) protected
D) static
Answer: C) protected
40. What is one common pattern to maintain invariants when multiple fields must change together?
A) Provide multiple independent setters that each update one field
B) Expose fields as public and let callers change them directly
C) Provide methods that update groups of fields atomically and validate combined state
D) Use only getters and no setters
Answer: C) Provide methods that update groups of fields atomically and validate combined state
41. Which of the following would be considered a breach of encapsulation in a library API?
A) Documenting behavior and returning interfaces
B) Exposing internal helper classes in the public API that clients begin to depend on
C) Providing factory methods instead of constructors
D) Using access modifiers to hide implementation classes
Answer: B) Exposing internal helper classes in the public API that clients begin to depend on
42. How does the Open/Closed Principle relate to encapsulation?
A) It contradicts encapsulation entirely
B) Encapsulation allows internal changes without altering external interfaces, enabling classes to be open for extension but closed for modification
C) It enforces public fields to be modifiable
D) It requires rewriting all client code on internals change
Answer: B) Encapsulation allows internal changes without altering external interfaces, enabling classes to be open for extension but closed for modification
43. Which practice makes it easier to change an object’s internal data structure later without affecting clients?
A) Returning concrete collection classes directly
B) Using interfaces or abstract types in method signatures and returning immutable wrappers when necessary
C) Exposing internal arrays directly
D) Using global variables for data
Answer: B) Using interfaces or abstract types in method signatures and returning immutable wrappers when necessary
44. What is a “defensive setter”?
A) A setter that ignores values passed by callers
B) A setter that validates input and enforces invariants before changing internal state
C) A setter that sleeps before setting a field
D) A setter that always throws an exception
Answer: B) A setter that validates input and enforces invariants before changing internal state
45. Which of the following best explains why encapsulation aids concurrency control?
A) Encapsulation prevents all concurrent operations
B) Encapsulation centralizes mutations, so synchronization or immutable snapshots can be applied in one place
C) Encapsulation eliminates the need for locks
D) Encapsulation copies objects for each thread automatically
Answer: B) Encapsulation centralizes mutations, so synchronization or immutable snapshots can be applied in one place
46. When might you intentionally relax encapsulation?
A) Never — encapsulation must always be strict
B) When performance is critical and well-documented, or for internal-only code where controlled exposure is acceptable (but must be justified)
C) When you want to make design unclear
D) For all public API design
Answer: B) When performance is critical and well-documented, or for internal-only code where controlled exposure is acceptable (but must be justified)
47. Which principle advises “Talk to friends, not strangers” and is relevant to encapsulation and object interaction?
A) Single Responsibility Principle
B) Law of Demeter (Principle of Least Knowledge)
C) Don’t Repeat Yourself
D) KISS
Answer: B) Law of Demeter (Principle of Least Knowledge)
48. Which is the best way to provide read-only access to a private numeric field in Java?
A) public int value;
B) public void getValue() { return value; }
C) public int getValue() { return value; }
D) public int[] getValue() { return new int[] { value }; }
Answer: C) public int getValue() { return value; }
49. What is the effect of making a field final in Java (with respect to encapsulation)?
A) It allows the field to be modified anytime
B) It ensures the field reference cannot be changed after initialization (helps create immutable aspects)
C) It makes the field public
D) It removes the need for getters
Answer: B) It ensures the field reference cannot be changed after initialization (helps create immutable aspects)
50. Which scenario requires defensive copying to preserve encapsulation?
A) Returning a new immutable string
B) Returning a reference to an internal Date or mutable collection directly
C) Returning primitives
D) Returning static constants
Answer: B) Returning a reference to an internal Date or mutable collection directly
51. Which of these statements about JavaBean conventions (getters/setters) is true in relation to encapsulation?
A) JavaBean setters must be public or they are invalid
B) JavaBean conventions encourage encapsulation by naming accessors, but careless use may expose too much internal state
C) JavaBeans forbid private fields
D) JavaBeans require fields to be final
Answer: B) JavaBean conventions encourage encapsulation by naming accessors, but careless use may expose too much internal state
52. In C++, how can a class ensure certain fields are writable only at construction time?
A) Use public fields and comments
B) Declare the fields const or initialize them in the constructor and do not provide modifying methods
C) Use global variables
D) Provide multiple setters
Answer: B) Declare the fields const or initialize them in the constructor and do not provide modifying methods
53. Which of the following is NOT part of encapsulation strategy?
A) Using private/protected fields
B) Providing controlled public interfaces for required operations
C) Hiding implementation details from clients
D) Making all classes static utility classes with public mutable fields
Answer: D) Making all classes static utility classes with public mutable fields
54. What is a “read-only view” and how does it support encapsulation?
A) A view that lets you change internal data silently
B) A read-only view provides access to internal data without giving modification rights, preventing accidental modification by clients
C) A view that deletes data on access
D) A view that makes objects mutable
Answer: B) A read-only view provides access to internal data without giving modification rights, preventing accidental modification by clients
55. Which statement correctly relates encapsulation and serialization?
A) Serialization always respects encapsulation and never accesses private fields
B) Serialization often requires access to internal state; special care is needed to ensure invariants are preserved when deserializing private data
C) Serialization cannot be used with encapsulated objects
D) Serialization automatically validates invariants after loading
Answer: B) Serialization often requires access to internal state; special care is needed to ensure invariants are preserved when deserializing private data
56. A class exposes a method getInternalArray() returning a direct reference to its private array. Which fix preserves encapsulation?
A) Make the array public instead
B) Return the array directly anyway
C) Return a defensive copy of the array or an unmodifiable wrapper
D) Remove the array entirely
Answer: C) Return a defensive copy of the array or an unmodifiable wrapper
57. Which of the following best captures the relationship between encapsulation and APIs?
A) APIs should expose as much internal detail as possible to reduce abstraction costs
B) APIs should expose only necessary operations and hide internal representation to allow future changes
C) APIs must always be implemented as free functions to avoid encapsulation
D) APIs and encapsulation are unrelated
Answer: B) APIs should expose only necessary operations and hide internal representation to allow future changes
58. Which is true about encapsulation and inheritance?
A) Inheritance always preserves encapsulation of the parent class
B) Subclasses can break parent encapsulation if protected or package access exposes internals, so design must be careful
C) Private members are always accessible to subclasses
D) Inheritance replaces encapsulation entirely
Answer: B) Subclasses can break parent encapsulation if protected or package access exposes internals, so design must be careful
59. What role do interfaces play in encapsulation?
A) Interfaces are concrete classes exposing internals
B) Interfaces hide implementation details by specifying behavior while allowing multiple hidden implementations
C) Interfaces force public fields
D) Interfaces remove the need for access control
Answer: B) Interfaces hide implementation details by specifying behavior while allowing multiple hidden implementations
60. Which approach best prevents clients from creating invalid object states?
A) Provide public setters for all fields without checks
B) Provide constructors and factory methods that validate inputs and keep fields private, restrict setters or avoid them entirely
C) Use global variables to store state
D) Allow callers to modify fields directly
Answer: B) Provide constructors and factory methods that validate inputs and keep fields private, restrict setters or avoid them entirely
61. In Java, marking a method final has what direct effect on encapsulation?
A) It makes fields private
B) It prevents subclasses from overriding the method, which can help protect internal behavior from being changed by subclasses
C) It makes methods public by default
D) It removes the need for access modifiers
Answer: B) It prevents subclasses from overriding the method, which can help protect internal behavior from being changed by subclasses
62. Which of the following is a safe way to allow external modification of an internal map?
A) Return the internal map directly
B) Expose the internal map as a public field
C) Return an unmodifiable view of the map or provide controlled mutation methods
D) Serialize the map to string and return it
Answer: C) Return an unmodifiable view of the map or provide controlled mutation methods
63. Which of the following best expresses why you wouldn’t test private methods directly in unit tests?
A) Private methods are always buggy
B) Private methods are implementation details; tests should validate public behavior to avoid coupling tests to internals
C) Private methods are unreachable and therefore not testable
D) Private methods are guaranteed correct
Answer: B) Private methods are implementation details; tests should validate public behavior to avoid coupling tests to internals
64. How can dependency injection help with encapsulation?
A) It eliminates the need for private fields
B) It allows replacing internal collaborators without exposing internal structure, promoting decoupling and encapsulation
C) It forces all dependencies to be public
D) It prevents polymorphism
Answer: B) It allows replacing internal collaborators without exposing internal structure, promoting decoupling and encapsulation
65. Which of the following is true for the “tell, don’t ask” principle and encapsulation?
A) It encourages asking for internal state from objects
B) It recommends instructing objects to perform actions rather than extracting their state and making decisions externally, supporting encapsulation
C) It is unrelated to encapsulation
D) It requires public fields for data access
Answer: B) It recommends instructing objects to perform actions rather than extracting their state and making decisions externally, supporting encapsulation
66. In Python, which naming convention indicates a member is intended to be private (not strictly enforced by language)?
A) Single leading underscore _name
B) Double trailing underscore name__
C) No underscore name
D) All caps NAME
Answer: A) Single leading underscore _name
67. Which of these choices properly defends an object against illegal external mutation of nested mutable fields?
A) Returning nested mutable fields directly
B) Returning deep copies or immutable wrappers of nested structures
C) Making nested fields public for convenience
D) Documenting that callers should not mutate nested fields
Answer: B) Returning deep copies or immutable wrappers of nested structures
68. Which practice reduces the risk that subclasses will depend on fragile parent internals?
A) Making internal fields protected and changing them often
B) Keeping fields private and exposing behavior through protected or public methods with stable semantics
C) Exposing many helper methods as public so subclasses can use internals
D) Forbidding subclassing entirely always
Answer: B) Keeping fields private and exposing behavior through protected or public methods with stable semantics
69. What is the best description of an accessor method?
A) A method that modifies internal state without restrictions
B) A method that returns information about an object’s state without modifying it
C) A method that compiles code
D) A global function unrelated to objects
Answer: B) A method that returns information about an object’s state without modifying it
70. Which scenario demonstrates encapsulation enabling backward-compatible changes?
A) Changing a public field type while clients access it directly
B) Replacing an internal data structure (e.g., ArrayList -> LinkedList) while method signatures and behavior remain the same
C) Removing a public method used by many clients without replacement
D) Exposing more internals to clients for performance
Answer: B) Replacing an internal data structure (e.g., ArrayList -> LinkedList) while method signatures and behavior remain the same
71. Which of the following demonstrates poor encapsulation when designing an exception class?
A) Providing constructors that ensure message and cause consistency
B) Storing internal state privately and exposing only necessary getters
C) Allowing client code to directly modify internal exception fields after construction
D) Keeping exceptions immutable after creation
Answer: C) Allowing client code to directly modify internal exception fields after construction
72. What is the relationship between encapsulation and the Single Responsibility Principle (SRP)?
A) Encapsulation and SRP are unrelated
B) Proper encapsulation helps keep responsibilities localized, making it easier to satisfy SRP
C) SRP requires public mutable state
D) Encapsulation prevents SRP from being applied
Answer: B) Proper encapsulation helps keep responsibilities localized, making it easier to satisfy SRP
73. Which of the following is most likely a sign of poor encapsulation in class design?
A) Many small private helper methods
B) A single class with dozens of public fields and responsibilities
C) Well-documented public interface with private internals
D) Use of interfaces to hide implementations
Answer: B) A single class with dozens of public fields and responsibilities
74. What is the advantage of using factory methods over public constructors for encapsulation?
A) Constructors are always better than factory methods
B) Factory methods can return different implementations and encapsulate the construction logic, hiding concrete types
C) Factory methods expose internal fields directly
D) Factory methods force fields to be public
Answer: B) Factory methods can return different implementations and encapsulate the construction logic, hiding concrete types
75. Which of these is an encapsulation-friendly approach to exposing an object’s size?
A) public int size;
B) public int getSize() { return internalCollection.size(); }
C) public int[] size;
D) public void setSize(int s) { size = s; }
Answer: B) public int getSize() { return internalCollection.size(); }
76. Which of these increases encapsulation safety when deserializing objects?
A) Allowing direct field assignment from serialized data without checks
B) Using custom deserialization logic that validates and reconstructs objects to maintain invariants
C) Skipping validation entirely for performance
D) Making all fields public and writable
Answer: B) Using custom deserialization logic that validates and reconstructs objects to maintain invariants
77. Which option best preserves encapsulation when extending functionality in subclasses?
A) Change parent private fields directly from subclass
B) Use protected or public methods defined by the base class to extend behavior while leaving private fields encapsulated
C) Add public fields to the subclass exposing parent internals
D) Recompile all client code after every change
Answer: B) Use protected or public methods defined by the base class to extend behavior while leaving private fields encapsulated
78. Which of the following statements about encapsulation and performance is true?
A) Encapsulation always makes code slower and should be avoided
B) Encapsulation can add minor overhead but the benefits (maintainability, correctness) usually outweigh costs; micro-optimizations can be applied conservatively
C) Encapsulation doubles memory usage
D) Encapsulation prevents inlining by compilers always
Answer: B) Encapsulation can add minor overhead but the benefits (maintainability, correctness) usually outweigh costs; micro-optimizations can be applied conservatively
79. In a multi-module project, what architectural choice supports encapsulation across module boundaries?
A) Make all classes public and mutable
B) Design clear module interfaces and keep implementation classes internal to the module
C) Use a single global namespace for everything
D) Share internal implementation classes between modules freely
Answer: B) Design clear module interfaces and keep implementation classes internal to the module
80. Which of these is an anti-pattern with respect to encapsulation?
A) Encapsulating state and behavior in objects
B) Exposing “God objects” with global mutable state and many public fields
C) Returning interfaces rather than concrete implementations
D) Using defensive copies where necessary
Answer: B) Exposing “God objects” with global mutable state and many public fields
81. How does encapsulation help in applying security principles?
A) It makes code less secure by hiding behavior
B) It restricts direct access to sensitive fields, allowing validation, access control, or redaction in one place
C) It replaces the need for authentication
D) It always encrypts fields automatically
Answer: B) It restricts direct access to sensitive fields, allowing validation, access control, or redaction in one place
82. What does “encapsulation boundary” refer to?
A) Memory limits of an object
B) The public interface that a component exposes, separating it from its internal implementation details
C) The physical boundary of a server
D) The network firewall rules for objects
Answer: B) The public interface that a component exposes, separating it from its internal implementation details
83. Which of the following is a correct encapsulation-based reason to prefer methods over exposing raw fields?
A) Methods prevent the compiler from inlining code
B) Methods allow invariants, lazy initialization, caching, and logging without revealing internal representation
C) Methods always use more CPU cycles so they are safer
D) Methods prevent object cloning
Answer: B) Methods allow invariants, lazy initialization, caching, and logging without revealing internal representation
84. Which approach supports encapsulation when passing large internal collections to callers?
A) Pass internal references directly for speed
B) Provide paged access, iterators, or read-only views to avoid exposing full internal collection
C) Make collections global variables
D) Remove all encapsulation and document usage rules
Answer: B) Provide paged access, iterators, or read-only views to avoid exposing full internal collection
85. Which of these is a reason to use accessors that compute values rather than returning fields directly?
A) To force callers to compute values repeatedly
B) To encapsulate derived state and allow internal representation changes without affecting callers
C) To increase code verbosity only
D) To prevent polymorphism
Answer: B) To encapsulate derived state and allow internal representation changes without affecting callers
86. Which of these demonstrates correctly handling encapsulation in a value object?
A) Mutable fields and many setters
B) Immutable fields, private state, and no setters — only accessors that return values
C) Public arrays as fields
D) Exposing internal state via global variables
Answer: B) Immutable fields, private state, and no setters — only accessors that return values
87. Which of the following helps maintain encapsulation while providing extensibility?
A) Exposing internal helper classes publicly
B) Using abstract base classes or interfaces with well-documented contracts, hiding implementations
C) Allowing subclasses to change private fields directly
D) Avoiding any abstraction and exposing everything
Answer: B) Using abstract base classes or interfaces with well-documented contracts, hiding implementations
88. What is an effect of excessive exposure of internal details in APIs?
A) Easier refactoring later
B) Clients become tightly coupled to internals, making refactoring costly and error-prone
C) Improved encapsulation
D) Safer concurrency
Answer: B) Clients become tightly coupled to internals, making refactoring costly and error-prone
89. Which of the following is an example of good encapsulation when designing a banking Account class?
A) public double balance;
B) public void withdraw(double amt) { if (amt>0 && amt<=balance) balance -= amt; } with balance private
C) public void withdraw(double amt) { balance -= amt; } with balance public
D) public double[] getTransactions() { return transactions; } // returns internal array
Answer: B) public void withdraw(double amt) { if (amt>0 && amt<=balance) balance -= amt; } with balance private
90. Which of these is the best encapsulation approach for configuration data read from disk?
A) Make configuration map public and mutable
B) Load configuration into a private immutable object and expose only safe accessors
C) Let callers read the disk file directly whenever needed
D) Use global mutable variables for config values
Answer: B) Load configuration into a private immutable object and expose only safe accessors
91. Which of these statements about encapsulation and refactoring is true?
A) Encapsulation makes refactoring impossible
B) Encapsulation reduces the blast radius of refactoring because internals are hidden behind stable interfaces
C) Refactoring requires all fields to be public
D) Encapsulation prevents optimization by compilers
Answer: B) Encapsulation reduces the blast radius of refactoring because internals are hidden behind stable interfaces
92. Why might you use package-private or module-private visibility rather than public?
A) To increase accidental usage by unrelated clients
B) To allow controlled access to internals by related classes while preventing wider public misuse
C) To make members visible across the whole internet
D) To avoid writing tests
Answer: B) To allow controlled access to internals by related classes while preventing wider public misuse
93. Which encapsulation technique can help when an object must expose a limited set of modifications?
A) Give direct access to internal lists
B) Provide specific mutator methods (e.g., addItem, removeItem) rather than a general setter
C) Make all fields public and mutable
D) Allow callers to clear internal structures directly
Answer: B) Provide specific mutator methods (e.g., addItem, removeItem) rather than a general setter
94. In languages with properties (e.g., C#), what does using a private setter accomplish?
A) It makes property public and writable by everyone
B) Allows read access publicly while restricting write access to the class itself, preserving encapsulation
C) It prevents reading the property
D) It removes encapsulation completely
Answer: B) Allows read access publicly while restricting write access to the class itself, preserving encapsulation
95. Which of the following is a sign that a class is well-encapsulated?
A) Many public mutable fields and no invariants
B) Small public surface area, clear responsibilities, private internals and behavior-exposing methods
C) Large number of global variables used by the class
D) All methods are static and reference global data
Answer: B) Small public surface area, clear responsibilities, private internals and behavior-exposing methods
96. What is the effect of exposing internal implementation classes as part of a public API?
A) Clients can be insulated from internal changes
B) Clients may depend on those implementation details, making future internal changes breaking
C) It improves encapsulation by default
D) It reduces coupling
Answer: B) Clients may depend on those implementation details, making future internal changes breaking
97. Which of these is an advantage of making fields private and giving only necessary behavior methods?
A) Increased risk of accidental modifications
B) Better control over state changes, easier debugging, and ability to enforce invariants
C) It always makes the program slower by orders of magnitude
D) It prevents all subclassing
Answer: B) Better control over state changes, easier debugging, and ability to enforce invariants
98. Which of the following patterns specifically addresses exposing a stable API while keeping many implementation details hidden?
A) Iterator pattern only
B) Facade and Adapter patterns help provide a stable surface while hiding internal complexities
C) Template method exclusively
D) Using public fields only
Answer: B) Facade and Adapter patterns help provide a stable surface while hiding internal complexities
99. When should you choose to return an immutable DTO (data transfer object) rather than a mutable object reference?
A) When you want callers to modify internal state directly
B) When you want to ensure internal state cannot be altered by callers and to preserve encapsulation across boundaries
C) When performance is the only concern and safety is irrelevant
D) When the DTO contains only primitive references and never objects
Answer: B) When you want to ensure internal state cannot be altered by callers and to preserve encapsulation across boundaries
100. Which of the following summarizes the most important practical guideline for encapsulation?
A) Make everything public to simplify coding
B) Minimize the public surface area — expose only what clients need; keep internals private and provide controlled, validated access
C) Only use protected fields everywhere
D) Avoid interfaces and always expose concrete classes
Answer: B) Minimize the public surface area — expose only what clients need; keep internals private and provide controlled, validated access
