OOP Interview Questions
- Encapsulation: Bundling data (attributes) and methods (behavior) that operate on that data within a single unit (class), and restricting direct access to some of an object's components.
- Use private/protected attributes with public getters/setters.
-
Benefit: Hides implementation details, reduces complexity, protects data integrity.
-
Abstraction: Hiding complex implementation details and showing only the essential features of an object.
- Achieved via abstract classes and interfaces.
-
Benefit: Reduces complexity, isolates changes, improves code readability.
-
Inheritance: A mechanism where a new class (child) derives properties and behaviors from an existing class (parent).
- Supports code reuse and establishes a hierarchical relationship.
- Benefit: Eliminates redundant code, models real-world 'is-a' relationships.
-
Note: Favor composition over inheritance to avoid deep, fragile hierarchies.
-
Polymorphism: The ability of an object to take on many forms. The same method call can behave differently based on the object's actual type.
- Compile-time (Method Overloading): Multiple methods with the same name but different parameters.
- Runtime (Method Overriding): A subclass provides a specific implementation of a method defined in its parent.
- Benefit: Code flexibility, extensibility, and interface-based design.
Key Points
Encapsulation, Abstraction, Inheritance, Polymorphism, Overloading vs Overriding, Composition over Inheritance
Common Follow-ups
What is the difference between an abstract class and an interface? When would you use each?
SOLID is a set of five design principles for writing maintainable, scalable object-oriented code:
- S — Single Responsibility Principle (SRP): A class should have only one reason to change — one job.
- O — Open/Closed Principle (OCP): Classes should be open for extension but closed for modification. Use interfaces/abstract classes.
- L — Liskov Substitution Principle (LSP): Subtypes must be substitutable for their base types without breaking correctness.
- I — Interface Segregation Principle (ISP): Many specific interfaces are better than one general-purpose interface.
- D — Dependency Inversion Principle (DIP): Depend on abstractions, not concrete implementations. High-level modules should not depend on low-level modules.
Why SOLID matters? - Reduces coupling between components. - Makes code easier to test (unit testing with mocks). - Allows teams to work on different parts of the codebase independently. - Enables refactoring and extension without breaking existing functionality.
Real-world example: A PaymentProcessor interface allows adding new payment methods (PayPal, Stripe, Crypto) without modifying existing code — following OCP.
Key Points
SOLID acronym, Loose coupling, Testability, Extensibility, Design patterns foundation
Common Follow-ups
Describe a design pattern you've used that aligns with these principles.