Bird
0
0

Identify the error in this Java class and fix it:

medium📝 Debug Q14 of 15
Java - Constructors
Identify the error in this Java class and fix it:
class Person {
  String name;
  Person() {
    name = "Unknown";
  }
  Person(String n) {
    name = n;
  }
  void display() {
    System.out.println("Name: " + name);
  }
}
public class Test {
  public static void main(String[] args) {
    Person p = new Person();
    p.display();
  }
}
ADisplay method should be static
BConstructor should have a return type
CName variable should be static
DMissing parentheses when calling constructor: use new Person()
Step-by-Step Solution
Solution:
  1. Step 1: Check object creation syntax

    In Java, when creating an object, parentheses must follow the constructor name even if empty.
  2. Step 2: Identify the error in main method

    The code uses 'new Person;' missing parentheses, causing a compile error.
  3. Final Answer:

    Missing parentheses when calling constructor: use new Person() -> Option D
  4. Quick Check:

    Object creation needs parentheses = C [OK]
Quick Trick: Always use parentheses after constructor name when creating objects [OK]
Common Mistakes:
  • Omitting parentheses in new object creation
  • Adding return type to constructors
  • Making display method static unnecessarily

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Java Quizzes