02 / 11

How would you design a system for a Car that has different engine types (Petrol, Diesel, Electric)? Show the OOP model.

Difficulty: 6/10
inheritance, polymorphism, factory pattern

Car and Engine Using Composition

I would model Car and Engine using composition rather than creating separate inheritance hierarchies such as PetrolCar, DieselCar, and ElectricCar. The Car depends on an IEngine abstraction, and concrete engines implement the behavior. This follows programming to an interface and makes adding another engine type possible without modifying Car.

javascript
  1. 1

    Car has an Engine rather than inheriting from an engine.

  2. 2

    The engine abstraction isolates Car from concrete engine implementations.

  3. 3

    New engines can be introduced without modifying Car.

  4. 4

    Dependency injection can select the engine at runtime or configuration time.

  5. 5

    This design supports Open/Closed Principle and composition over inheritance.

Scenario Questions

0-2 years experience

  1. 1Write a minimal class hierarchy for Engine, PetrolEngine, DieselEngine, and ElectricEngine, and show how a Car object uses it.
  2. 2If you call car.start() on a Car that holds an ElectricEngine, which method gets executed and why?

2-5 years experience

  1. 1We need to add a new HydrogenEngine without modifying the Car class. How would you refactor your design to satisfy the open/closed principle?
  2. 2A bug appears where a DieselEngine throws a NullPointerException when getFuelEfficiency() is called. Walk me through how you would locate and fix the issue.
  3. 3Discuss the trade‑offs between using inheritance versus composition for modeling the engine types.

5-8 years experience

  1. 1Our fleet service serializes Car objects to JSON for storage. What design considerations does this impose on your Engine hierarchy?
  2. 2If the system must allow hot‑swapping an engine while the car is running, how would you adapt the OOP model?
  3. 3Compare using a static Factory method versus reflection for creating engine instances when we need to support thousands of car configurations.

8+ years experience

  1. 1We are migrating a legacy C++ vehicle control system to a microservice architecture in Java. How would you design the engine abstraction to keep services loosely coupled?
  2. 2How would you ensure backward compatibility for existing car models while rolling out a new electric drivetrain across multiple product teams?
  3. 3What governance or ownership model would you put in place for the engine hierarchy to prevent combinatorial explosion as more powertrain variants are added?

Follow-up Questions

  • How would you add a hybrid engine without touching existing classes?
  • What changes are needed if the engine type must be swapped at runtime?
  • How does your design affect unit testing of the Car class?
Share

Share via WhatsApp, X, Facebook, LinkedIn or copy link. Open Graph preview enabled.