1Z0-819 · Question #25
Given: public class Person { private String name = "Joe Bloggs"; public Person(String name) { this.name = name; } public String toString() { return name; } } and public class Tester { public static…
The correct answer is B. Joe Bloggs. There's actually an error in the provided answer key - option C is the correct answer, not B. Person defines an explicit constructor Person(String name), which means Java does not auto-generate a no-arg constructor. Line 1 calls new Person() with no arguments, so the compiler…
Question
Options
- Anull
- BJoe Bloggs
- CThe compilation fails due to an er or in line 1.
- Dp1
How the community answered
(48 responses)- A6% (3)
- B79% (38)
- C13% (6)
- D2% (1)
Explanation
There's actually an error in the provided answer key - option C is the correct answer, not B.
Person defines an explicit constructor Person(String name), which means Java does not auto-generate a no-arg constructor. Line 1 calls new Person() with no arguments, so the compiler finds no matching constructor and fails with a compilation error. Option B ("Joe Bloggs") would only be reachable if the code actually compiled and ran - the field initializer name = "Joe Bloggs" is immediately overwritten by any Person(String name) call anyway, so B could never be printed via a no-arg path. Option A ("null") is wrong for the same reason - execution never begins. Option D ("p1") is a nonsensical distractor; p is the variable name, not p1, and toString() returns name, not the variable name regardless.
Memory tip: In Java, the free no-arg constructor disappears the moment you write any explicit constructor. Think of it as: "define one, you own them all" - if you want both, you must write both.
Topics
Community Discussion
No community discussion yet for this question.