Bird
0
0

Identify the error in this Java class modeling a Person:

medium📝 Debug Q14 of 15
Java - Object-Oriented Programming Concepts
Identify the error in this Java class modeling a Person:
public class Person {
  String name;
  int age;

  void Person(String n, int a) {
    name = n;
    age = a;
  }
}
AConstructor has void return type, so it's a method, not a constructor
BMissing semicolon after variable declarations
CClass name should be lowercase
DVariables should be private
Step-by-Step Solution
Solution:
  1. Step 1: Check constructor syntax

    Constructors in Java do not have a return type. Here, void Person(...) is a method, not a constructor.
  2. Step 2: Understand impact of error

    Because of void, this method won't initialize the object when created, causing default values.
  3. Final Answer:

    Constructor has void return type, so it's a method, not a constructor -> Option A
  4. Quick Check:

    Constructor = no return type [OK]
Quick Trick: Constructors never have a return type, not even void [OK]
Common Mistakes:
  • Thinking void is needed for constructors
  • Ignoring constructor syntax rules
  • Confusing methods with constructors

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Java Quizzes