Interview Q&A / Object-Oriented Programming
Object-Oriented Programming interview questions
The four pillars, interfaces, abstract classes and design basics.
Prefer rapid revision? Practise Object-Oriented Programming short interview answers →
- What is the difference between composition and inheritance, and when would you prefer composition?
Inheritance is an "is-a" relationship where a class extends another and reuses its code. Composition is a "has-a" relationship where a class holds other objects and delegates work to them. Prefer composition by default because it keeps classes loosely coupled and lets you swap behaviour, and use inheritance only for a true, stable "is-a" relationship.
IntermediateIn-depth3 min read - Does the Single Responsibility Principle mean a class should have only one method?
No. It means a class should have one reason to change, serving one actor or concern. A class can have many methods if they all serve that single purpose.
BeginnerQuick answer1 min read - What are constructor injection and setter injection, and which should you prefer?
Constructor injection passes dependencies when the object is created, so it is never half-built. Setter injection sets them afterwards. Prefer the constructor for required dependencies and setters only for optional ones.
BeginnerQuick answer1 min read - Why is creating dependencies with new inside a class considered a problem?
It hard-wires the class to one concrete implementation, hides what it depends on, and makes it impossible to replace in tests or in other environments without editing the class.
BeginnerQuick answer1 min read - Does the Open/Closed Principle mean you can never edit an existing class?
No. You still fix bugs and change requirements. OCP is about designing so that common kinds of change, such as adding a new variant, need new code instead of edits to old code.
IntermediateQuick answer1 min read - How do you create an immutable class in Java?
Make the class final, all fields private and final, set them only in the constructor, add no setters, and copy any mutable object on the way in and on the way out.
IntermediateQuick answer1 min read - What is a leaky abstraction?
A leaky abstraction promises to hide a detail but fails in some situations, so the user has to understand the hidden layer anyway. The simple view stops being enough.
AdvancedQuick answer1 min read