ProgrammingHardProduct-company placement · Java
Which line fails to compile?
Which line fails to compile?
class Outer {
int x = 1;
class In { int get() { return x; } }
static class SN { int get() { return 2; } }
}
// in main (a static method of another class):
Outer.SN a = new Outer.SN(); // L1
Outer.In b = new Outer.In(); // L2
Outer.In c = new Outer().new In(); // L3- A. L1 only
- B. L1 and L2
- C. L2 only
- D. None of them
Correct answer: C. L2 only
A static nested class needs no outer object (L1). An inner (non-static) class instance is tied to an Outer instance, so it must be created as outerRef.new In() (L3); L2 has no enclosing instance.
More OOP with C++ and Java questions
- What is printed? java class Outer { int x = 1; class Inner { int x = 2; void show(int x) { System.out.print(x + " " + this.x + " " +…
- What is printed? java int count = 0; Runnable r = () -> System.out.print(count); count++; r.run();
- What is printed? java enum Level { LOW(1), HIGH(3); Level(int v) { System.out.print(name() + v + " "); } static { System.out.print("S ")…
- What is printed? java enum Dir { N, E, S, W } // in main: System.out.print(Dir.values()[2] + " " + Dir.valueOf("W").ordinal() + " ")…
- What is printed? java class Box implements Cloneable { int[] data = {1, 2}; int n = 5; public Box clone() throws…
- What is printed? java // static method of the main class: static void swap(int[] a, int[] b) { int[] t = a; a = b; b = t; a[0] = 100; } //…