1Z0-819 · Question #187
What change will cause the code to compile successfully? Given: public class Electronics { public Electronics(double price) { super(); } } and public class Plushy extends Electronics { public…
The correct answer is A. Insert `PriceChecker (?) prod` on line 1. Option A uses PriceChecker<?> (the wildcard type), which declares a single prod variable that can hold either PriceChecker<Electronics> or PriceChecker<Plushy>. This resolves the duplicate variable name - instead of two separate declarations, you declare prod once with the…
Question
Options
- AInsert
PriceChecker (?) prodon line 1. - BInsert
PriceChecker <Electronics> prodon line 1. - CInsert
PriceChecker <Plushy> prodon line 1. - DInsert
PriceChecker <Object> prodon line 1.
How the community answered
(45 responses)- A84% (38)
- B2% (1)
- C9% (4)
- D4% (2)
Explanation
Option A uses PriceChecker<?> (the wildcard type), which declares a single prod variable that can hold either PriceChecker<Electronics> or PriceChecker<Plushy>. This resolves the duplicate variable name - instead of two separate declarations, you declare prod once with the wildcard, then reassign it: the wildcard ? is compatible with any type argument that satisfies the class-level bound (T extends Electronics).
Why the others fail:
- B (
PriceChecker<Electronics>) won't work because Java generics are invariant -PriceChecker<Plushy>is not a subtype ofPriceChecker<Electronics>, so the reassignment would cause a compile error. - C (
PriceChecker<Plushy>) fails for the same invariance reason in reverse -PriceChecker<Electronics>is not a subtype ofPriceChecker<Plushy>. - D (
PriceChecker<Object>) violates the class's generic bound<T extends Electronics>-Objectdoesn't extendElectronics, so the compiler rejects it outright.
Memory tip: Unlike arrays, Java generics are invariant - List<Dog> is not a List<Animal>. When you need a single reference to hold multiple parameterized types, reach for the wildcard ?, which opts into the subtype flexibility that raw generics otherwise block.
Community Discussion
No community discussion yet for this question.