Practice
Elevator class implement an interface or extend an abstract class to represent different elevator types (e.g., passenger, freight)? Consider that elevators share common state and behavior but also have type-specific logic.Solution
Step 1: Analyze shared state and behavior
Elevators share common fields like currentFloor, direction, and doorStatus, plus some implemented methods.Step 2: Abstract class fits shared state and partial behavior
Abstract class allows code reuse and enforces common state, while subclasses override type-specific logic.Final Answer:
Option A -> Option AQuick Check:
Abstract class supports shared state and behavior [check]
Ball entity be modeled as an abstract class or an interface? Consider that Ball has state like ballNumber and behavior like calculateRuns(). Which is the best choice and why?Solution
Step 1: Analyze Ball's state and behavior
Ball has state (ballNumber) and behavior (calculateRuns), so it needs to store data and provide common logic.Step 2: Abstract class vs interface for state
Interfaces cannot hold instance state; abstract classes can hold state and provide shared implementation.Final Answer:
Option A -> Option AQuick Check:
Stateful entity with behavior -> abstract class [check]
Vehicle abstraction for a parking system, should Vehicle be an abstract class or an interface if it needs to hold state like licensePlate? Why?Solution
Step 1: Identify state holding needs
licensePlateis shared state, which interfaces cannot hold as fields.Step 2: Evaluate options
Abstract classes can hold state and provide default behavior; interfaces cannot hold instance fields, only constants.Final Answer:
Option D -> Option DQuick Check:
Abstract class holds shared state like licensePlate [check]
Solution
Step 1: Analyze shared code in states
Elevator states often share common fields (e.g., reference to context) and helper methods, which favors an abstract class.Step 2: Evaluate interface limitations
Interfaces cannot hold state or provide default implementations (prior to Java 8), so they are less suitable if shared code exists.Final Answer:
Option B -> Option BQuick Check:
Shared code and state -> abstract class [check]
WeekendFeeStrategy to calculate parking fees on weekends without modifying existing classes. Which SOLID principle guides this design and what is the minimum change?Solution
Step 1: Identify applicable SOLID principles
Open/Closed Principle (OCP) requires extending behavior without modifying existing code; Dependency Inversion Principle (DIP) requires depending on abstractions likeFeeStrategy.Step 2: Apply minimal change preserving OCP and DIP
ImplementWeekendFeeStrategyas a new class implementingFeeStrategyand inject it where needed, avoiding changes to existing classes.Final Answer:
Option A -> Option AQuick Check:
New strategy class + injection -> OCP and DIP preserved [check]
