Bird
0
0

Find the error in this Java code:

medium📝 Debug Q7 of 15
Java - Object-Oriented Programming Concepts
Find the error in this Java code:
class Person {
  private String name;
  public String getName() {
    return name;
  }
}
public class Test {
  public static void main(String[] args) {
    Person p = new Person();
    System.out.println(p.name);
  }
}
AMissing constructor in Person class
BgetName() method should be static
CCannot access private variable name directly
DNo error, code runs fine
Step-by-Step Solution
Solution:
  1. Step 1: Check access modifiers

    The variable 'name' is private in Person class, so it cannot be accessed directly outside the class.
  2. Step 2: Analyze code usage

    System.out.println(p.name); tries to access private variable directly, causing a compile-time error.
  3. Final Answer:

    Cannot access private variable name directly -> Option C
  4. Quick Check:

    Private variables need getters for outside access [OK]
Quick Trick: Private variables need getters to access outside class [OK]
Common Mistakes:
  • Trying to access private fields directly
  • Assuming missing constructor causes error
  • Thinking getters must be static

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Java Quizzes