Bird
0
0

Find the error in the following code snippet:

medium📝 Debug Q14 of 15
Java - Constructors

Find the error in the following code snippet:

class Person {
    String name;
    int age;
    Person(String n) {
        name = n;
    }
    Person(String n, int a) {
        name = n;
        age = a;
    }
    Person() {
        this("Unknown");
        this(0);
    }
}
AMissing return type in constructors.
BCannot call two constructors using 'this()' in the same constructor.
CConstructor names must be different for overloading.
DNo error; code is correct.
Step-by-Step Solution
Solution:
  1. Step 1: Analyze constructor chaining rules

    In Java, a constructor can call only one other constructor using 'this()' and it must be the first statement.
  2. Step 2: Identify the error in the no-argument constructor

    The no-argument constructor calls 'this("Unknown")' and then 'this(0)', which is not allowed.
  3. Final Answer:

    Cannot call two constructors using 'this()' in the same constructor. -> Option B
  4. Quick Check:

    Only one 'this()' call allowed per constructor [OK]
Quick Trick: Only one 'this()' call allowed as first line in constructor [OK]
Common Mistakes:
  • Trying to call multiple constructors with 'this()'
  • Thinking constructor names must differ
  • Forgetting 'this()' must be first statement

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Java Quizzes