ProgrammingVery hardProduct-company placement · Java

What is printed?

What is printed?
class A {
    private int v = 1;
    boolean same(A other) { return v == other.v; }
    void set(A other) { other.v = 9; }
}
// in main:
A p = new A(), q = new A();
p.set(q);
System.out.print(p.same(q));
  1. A. false
  2. B. true
  3. C. Compile-time error: v is private to each object
  4. D. Compile-time error at other.v = 9 only

Correct answer: A. false

In Java, private access is per CLASS, not per object: code in A may read and write the private field of any A. q.v becomes 9, so the comparison is 1 == 9, false.

More OOP with C++ and Java questions

Exams that ask this topic