Interview Q&A / Object-Oriented Programming

INTERVIEW Q&A · 69 QUESTIONS

Object-Oriented Programming interview questions

The four pillars, interfaces, abstract classes and design basics.

  1. 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
  2. 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
  3. 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