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. Are constructors and private members inherited in Java?

    Constructors are never inherited; a child must define its own and call the parent's with super(). Private members exist inside the child object but cannot be accessed by name from the child.

    IntermediateQuick answer1 min read
  3. What is the difference between protected and default (package-private) access in Java?

    Default access lets only classes in the same package use the member. Protected allows the same package plus subclasses in any package, but through inheritance.

    IntermediateQuick answer1 min read
  4. Why does Java not allow a class to extend two classes?

    To avoid the diamond problem: if two parents define the same method and a child inherits both, it is unclear which version should run. Java blocks it and lets you combine interfaces instead.

    IntermediateQuick answer1 min read
  5. Why does Square extending Rectangle violate the Liskov Substitution Principle?

    A Square must keep width and height equal, so setting one changes the other. Code written for any Rectangle, expecting independent sides, gets wrong results when given a Square.

    IntermediateQuick answer1 min read