Question 1
AdvancedUtilizing Java Object-Oriented Approach · Java Inheritance
Case Study:
A logistics company is modernizing its package tracking system. The system needs to represent different types of packages, each with specific attributes. The requirements are as follows:
- There are three and only three types of packages:
Standard,Express, andFragile. - No other package types should be permissible in the system to ensure strict domain modeling.
- A
Standardpackage has a weight. - An
Expresspackage has a weight and a priority level (an integer). - A
Fragilepackage has a weight and special handling instructions (a String). - All package types should be immutable data carriers.
A senior developer proposes using a combination of sealed interfaces and records to model this domain. The goal is to create a type-safe hierarchy that can be effectively processed, for example, in a switch expression for calculating shipping costs.
Which code implementation best satisfies all the given requirements?
Answer and explanation
Correct answer: B
This solution perfectly meets all requirements. The sealed interface Package with a permits clause ensures that only Standard, Express, and Fragile can implement it, satisfying requirement #1 and #2. Using record for each package type makes them immutable data carriers with appropriate fields, satisfying requirements #3, #4, #5, and #6. This structure is ideal for modern, type-safe domain modeling and works perfectly with pattern matching in switch expressions.
