Bird
0
0

You want to create a class Person that sets the name to "Unknown" by default if no name is given. Which constructor code correctly implements this using a default constructor?

hard📝 Application Q15 of 15
Java - Constructors
You want to create a class Person that sets the name to "Unknown" by default if no name is given. Which constructor code correctly implements this using a default constructor?
Apublic class Person { String name; public Person() { name = name; } }
Bpublic class Person { String name = "Unknown"; public Person(String name) { name = name; } }
Cpublic class Person { String name; public Person(String name) { this.name = name; } }
Dpublic class Person { String name; public Person() { name = "Unknown"; } public Person(String name) { this.name = name; } }
Step-by-Step Solution
Solution:
  1. Step 1: Check default constructor sets default value

    public class Person { String name; public Person() { name = "Unknown"; } public Person(String name) { this.name = name; } }'s default constructor sets name to "Unknown" correctly.
  2. Step 2: Verify parameterized constructor sets name properly

    public class Person { String name; public Person() { name = "Unknown"; } public Person(String name) { this.name = name; } } uses 'this.name = name;' to assign parameter to instance variable.
  3. Final Answer:

    public class Person { String name; public Person() { name = "Unknown"; } public Person(String name) { this.name = name; } } -> Option D
  4. Quick Check:

    Default constructor sets default value, parameterized sets given value [OK]
Quick Trick: Default constructor sets default values; use 'this' for parameters [OK]
Common Mistakes:
  • Assigning parameter to itself without 'this.'
  • Not setting default value in default constructor
  • Missing default constructor entirely

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Java Quizzes