Practice
OrderState be an abstract class or an interface? Consider that each state has different behavior but shares no common state variables. Which is the best choice and why?Solution
Step 1: Analyze state sharing needs
States have no shared variables, only behavior differences, so no need for shared state in a superclass.Step 2: Evaluate interface vs abstract class
Interface suits behavior contracts without state and allows flexibility; abstract class is unnecessary and restrictive here.Final Answer:
Option B -> Option BQuick Check:
Interface fits stateless behavior contracts best [check]
Vehicle base type be an abstract class or an interface? Why?Solution
Step 1: Consider cloning and shared state
Cloning often requires copying internal state; an abstract class can hold this state and provide a defaultclone()implementation.Step 2: Evaluate interface limitations
Interfaces define behavior but cannot hold state or provide default cloning logic (in Java before default methods). Thus, abstract class fits better.Final Answer:
Option A -> Option AQuick Check:
Abstract class holds state + cloning logic -> correct OOP design [check]
assignLocker() method is not synchronized, which exact sequence of thread interleaving causes two packages to be assigned the same locker?Solution
Step 1: Identify the check-then-act race condition
Without synchronization, Thread 1 reads locker as available, then context switches before marking it occupied.Step 2: Thread 2 also reads locker as available and proceeds to assign it, causing double-booking.
Both threads assign the same locker before either updates the status.Final Answer:
Option C -> Option CQuick Check:
Check-then-act gap -> double assignment [check]
parkVehicle() is not synchronized, which exact sequence of Thread 1 and Thread 2 causes double-booking of the same spot?Solution
Step 1: Identify the check-then-act race condition
Without synchronization, Thread 1 reads spot as available but before marking it occupied, context switches to Thread 2 which also reads it as available.Step 2: Both threads proceed to park, causing double-booking
Because the state update is not atomic, both threads park vehicles in the same spot simultaneously.Final Answer:
Option C -> Option CQuick Check:
Unsynchronized check-then-act -> double-booking race [check]
ElectricCar vehicles requiring ChargingSpot parking. What is the minimum change to the current Java design to support this without modifying existing classes?Solution
Step 1: Identify extensibility requirements
Adding ElectricCar and ChargingSpot must not modify existing classes to respect OCP and avoid class explosion.Step 2: Minimal change approach
Adding new enum values and creating new subclasses for ElectricCar and ChargingSpot, plus updating compatibility externally, extends functionality without changing existing code.Final Answer:
Option A -> Option AQuick Check:
New enums + subclasses + external compatibility update -> no existing class change [check]
