ProgrammingHardWipro · Cognizant pattern
What is printed?
What is printed?
class Outer {
static int x = 100;
static class Nested {
int x = 200;
void show() { System.out.println(x + " " + Outer.x); }
}
}
public class Main {
public static void main(String[] args) {
new Outer.Nested().show();
}
}- A. 200 100
- B. 100 200
- C. 200 200
- D. Compile-time error: Nested cannot access Outer.x without an Outer instance
Correct answer: A. 200 100
Nested is a static nested class, so it has no implicit reference to an enclosing Outer instance, but it can still freely access Outer's static members by qualifying them, Outer.x. show() prints its own instance field x (200) and then the qualified Outer.x (100).
More OOP with C++ and Java questions
- What is printed? cpp class Singleton { static Singleton instance; Singleton() { cout << "Created "; } public: static Singleton get() { if…
- What is printed? cpp struct Base { int level = 1; }; struct Mid : Base { int level = 2; }; struct Leaf : Mid { int level = 3; void show()…
- What is printed? java public class Main { static <T extends Comparable<T>> T max(T a, T b) { return a.compareTo(b) >= 0 ? a : b; } public…
- What is printed? java class Box<T> { private T value; void set(T v) { value = v; } T get() { return value; } } public class Main { public…
- What is printed? java public class Main { public static void main(String[] args) { Integer a = 127; Integer b = 127; Integer c = 200…
- What is printed? java class Point { int x, y; Point(int x, int y) { this.x = x; this.y = y; } @Override public boolean equals(Object o) {…