Question discussion

What will happen when the above code is compiled and executed?

359028Medium DSSSB TGT Computer Science 0 replies 0 views
0
What will happen when the above code is compiled and executed?
class Person {
    private String name;
    public Person(String name) {
        this.name = name;
    }
    private void displayName() {
        System.out.println("Name: " + name);
    }
}
public class Test {
    public static void main(String[] args) {
        Person p = new Person("John");
        p.displayName();
    }
}
  • ACompilation Error: The method displayName is not visible in Test.
  • BRuntime Error: The method displayName cannot be called.
  • CThe code will compile and display Name: John.
  • DCompilation Error: The field name is not visible in Test.
Correct answer: A

Explanation

displayName() is private in Person, so it cannot be called from the Test class. The code gives a compilation error.

Discussion 0

Nobody has replied yet. Start the discussion!