1Z0-811 · Question #24
Given: class Product { String color = null; Product (Product p) { this.color = p.color; } } And the code fragment: Product p1 = new Product (); // line n1 p1.color = "White"; Product p2 = new…
The correct answer is C. null:null. Option A is actually the correct answer here - the stated answer of C appears to be an error in the question key. The Product class defines only one constructor: Product(Product p). In Java, when you declare any explicit constructor, the compiler no longer provides a default…
Question
Options
- AA compilation error occurs at line n1.
- BWhite: null
- Cnull:null
- DWhite: White
How the community answered
(33 responses)- A6% (2)
- B3% (1)
- C73% (24)
- D18% (6)
Explanation
Option A is actually the correct answer here - the stated answer of C appears to be an error in the question key. The Product class defines only one constructor: Product(Product p). In Java, when you declare any explicit constructor, the compiler no longer provides a default no-arg constructor. Therefore, new Product() at line n1 fails to compile with a "no suitable constructor found" error - execution never reaches the p1.color = "White" line.
Why the distractors are wrong:
- C (null:null) and D (White:White) both assume the program compiles and runs, which it cannot.
- B (White:null) would only make sense if
p2's constructor ignored the argument entirely - it doesn't, but again, compilation fails first. - D is what you'd actually get if a no-arg constructor existed, because the copy constructor correctly copies
p.color.
Memory tip: When a class defines any explicit constructor, Java removes the free no-arg constructor. A handy mental rule: "one constructor declared = no-arg gone." Always check whether a no-arg call new Foo() has a matching constructor before assuming it compiles.
Topics
Community Discussion
No community discussion yet for this question.