Bird
0
0

Find the error in this code snippet:

medium📝 Debug Q7 of 15
Java - Classes and Objects
Find the error in this code snippet:
class Student {
  int id;
  String name;

  public Student(int id, String name) {
    id = id;
    name = name;
  }
}
AInstance variables are not assigned correctly due to shadowing.
BConstructor name is incorrect.
CMissing return type in constructor.
DInstance variables must be static.
Step-by-Step Solution
Solution:
  1. Step 1: Analyze variable assignment in constructor

    Parameters have same names as instance variables, causing shadowing. Assignments like 'id = id;' assign parameter to itself.
  2. Step 2: Correct assignment approach

    Use 'this.id = id;' and 'this.name = name;' to assign parameters to instance variables.
  3. Final Answer:

    Instance variables are not assigned correctly due to shadowing. -> Option A
  4. Quick Check:

    Use 'this' to avoid shadowing [OK]
Quick Trick: Use 'this' to refer to instance variables when shadowed. [OK]
Common Mistakes:
  • Assigning parameters to themselves instead of instance variables.
  • Thinking constructor name is wrong.
  • Assuming instance variables must be static.

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Java Quizzes