ProgrammingVery hardProduct-company placement · Java
What is printed?
What is printed?
class A { static int v = 1; static int get() { return v; } }
class B extends A { static int v = 2; }
// in main:
B.v++;
A.v += 10;
System.out.print(B.get() + " " + B.v + " " + A.v);- A. 11 3 11
- B. 3 3 11
- C. 12 2 11
- D. 11 3 12
Correct answer: A. 11 3 11
B declares its own static v that HIDES A.v, so B.v++ makes B.v = 3 while A.v becomes 11. B.get() is A's static method and reads A.v, i.e. 11.
More OOP with C++ and Java questions
- What happens when this code is compiled? java try { new java.io.FileReader("x.txt"); } catch (Exception e) { System.out.print("E"); }…
- What is printed? java // static method of the main class: static int f() { try { throw new RuntimeException("t"); } finally { return 7; }…
- What is printed? java try { try { throw new IllegalStateException("A"); } finally { throw new IllegalArgumentException("B"); } } catch…
- What is printed? java class K { static int v = 10 / Integer.parseInt("0"); } // in main: try { System.out.print(K.v); } catch…
- What is printed? java // static method of the main class: static void down() { down(); } // in main: try { down(); } catch (Exception e) {…
- What happens when this class is compiled? java class A { A() { this(1); } A(int x) { this(); } }