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));- A. false
- B. true
- C. Compile-time error: v is private to each object
- 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
- What is printed? cpp struct M { M(const char s) { cout << s; } }; struct S { M x, y; S() : y("Y"), x("X") { cout << "S"; } }; int main() {…
- What is printed? cpp struct B { virtual ~B() { hi(); } virtual void hi() { cout << "B"; } }; struct D : B { ~D() { cout << "~D "; } void…
- What is printed? cpp struct E { virtual const char what() const { return "E"; } }; struct F : E { const char what() const override {…
- What is printed? cpp struct E { }; struct F : E { }; int main() { try { throw F(); } catch (E&) { cout << "E"; } catch (F&) { cout << "F"…
- What is printed? cpp struct E { virtual void id() const { cout << "E"; } }; struct F : E { void id() const override { cout << "F"; } }…
- What is printed? cpp struct T { char c; T(char x) : c(x) { cout << c; } ~T() { cout << c << c; } }; void f() { T a('a'); T b('b'); throw…