OOP_Interview_Problems
OOP_Interview_Problems
What is the difference between composition and inheritance, and when would
you favor one over the other?
Inheritance models 'is-a' relationships, while composition models 'has-a' relationships.
Inheritance is tight coupling — changes in base class affect all subclasses.
Composition is more flexible and promotes loose coupling.
Preferred scenarios:
Use composition when behaviors can be shared or changed at runtime (e.g., Strategy
pattern).
Use inheritance for shared structure or when subclass truly is a specialized type of the
superclass.
Example:
Instead of class Car extends Vehicle, use Car has Engine, and inject different engine
types as needed.
Modern design favors composition over inheritance for flexibility and adherence to
SOLID principles.
How would you explain encapsulation and its practical benefits in a service-
based architecture?
Encapsulation is the principle of hiding internal details and exposing only what’s
necessary via a defined interface.
In service-based architecture, encapsulation helps enforce boundaries between
components.
Benefits:
Reduces the chance of unintended usage of internal logic or data.
Facilitates refactoring — changes in internal implementation don't affect consumers.
Improves security and robustness by validating input/output through public interfaces.
Example:
A UserService only exposes methods like createUser() or findUserById(), but hides
internal database queries or caching strategies.
How would you apply abstraction when designing APIs for external clients?
Abstraction hides implementation details and shows only essential operations.
When designing APIs:
Expose only business-relevant operations (e.g., /createOrder, /getCustomerProfile).
Hide database schema, internal IDs, or intermediate processing logic.
Techniques to implement abstraction:
Use DTOs to separate internal models from external representation.
Apply versioning to control and evolve exposed interfaces without breaking clients.
Benefits:
Improved security, decoupling, and maintainability.
Allows internal evolution without impacting consumers.