ProgrammingHardAmazon/Microsoft SDE MCQ · Java placement
What is printed?
What is printed?
class Outer {
int v = 1;
class Inner { int v = 2; int get() { return v + Outer.this.v; } }
static class Nest { int get() { return 3; } }
}
// in main:
Outer o = new Outer();
Outer.Inner in = o.new Inner();
Outer.Nest n = new Outer.Nest();
System.out.print(in.get() + n.get());- A. 6
- B. 5
- C. 33
- D. Compile error at o.new Inner()
Correct answer: A. 6
An inner (non-static) class needs an enclosing instance, created with o.new Inner(); its v is 2 and Outer.this.v is 1, so get() returns 3. A static nested class needs no instance and returns 3: 3 + 3 = 6.
More OOP with C++ and Java questions
- Which line fails to compile? java class P { void run() throws java.io.IOException { } } class A extends P { void run() { } } // line 1…
- What is printed? java String s = "java"; s.toUpperCase(); s.concat("x"); StringBuilder sb = new StringBuilder("java"); sb.reverse()…
- What is printed? java interface I { default String n() { return "I"; } } class P { public String n() { return "P"; } } class C extends P…
- What is printed (C++17)? cpp struct T { T() { } T(const T&) { cout << "C"; } T(T&&) { cout << "M"; } }; int main() { const T a; T b =…
- What is printed? cpp struct T { T() { } T(const T&) { cout << "C"; } }; struct W { T t; }; int main() { W a; W b = std::move(a); }
- What is printed? cpp struct A { virtual void f() = 0; }; void A::f() { cout << "A"; } struct B : A { void f() override { A::f(); cout <<…