nerdexam
Oracle

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

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 Plushy(double price) { super(price); } } and public class PriceChecker <T extends Electronics> { private T product; public PriceChecker (T product) { this.product = product; } public boolean isPriceEqual(double price) { return prod.product.getprice() == price; // line 1 } public static void main(String... args) { PriceChecker<Electronics> prod = new PriceChecker<>(new Electronics(1000.00)); PriceChecker<Plushy> prod = new PriceChecker<>(new Plushy(1.2)); // problem: variable prod already defined System.out.println(prod.isPriceEqual(b)); // problem: b not defined. } }

Options

  • AInsert PriceChecker (?) prod on line 1.
  • BInsert PriceChecker <Electronics> prod on line 1.
  • CInsert PriceChecker <Plushy> prod on line 1.
  • DInsert PriceChecker <Object> prod on line 1.

How the community answered

(45 responses)
  • A
    84% (38)
  • B
    2% (1)
  • C
    9% (4)
  • D
    4% (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 of PriceChecker<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 of PriceChecker<Plushy>.
  • D (PriceChecker<Object>) violates the class's generic bound <T extends Electronics> - Object doesn't extend Electronics, 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.

Full 1Z0-819 Practice