ProgrammingHardAccenture · Capgemini technical pattern
Class P is in package a and declares protected int x. Class C is in package b and extends P. Inside an instance method of C, which of these statements fails to compile? (1) x = 1; (2) this.x = 1; (3) new P().x = 1;
- A. Only (3)
- B. Only (1) and (2)
- C. All three
- D. None of them
Correct answer: A. Only (3)
Outside its package, a protected member can be accessed by a subclass only through references of the subclass type (or its own subtypes). x and this.x are accessed via C, so they compile; new P().x goes through a plain P reference, which is not allowed.
More OOP with C++ and Java questions
- What happens when this Java class is compiled? java class Util { static void f(List<String> l) { } static void f(List<Integer> l) { } }
- How many of the following statements about equals() and hashCode() in Java are correct? (i) If a.equals(b) is true, a.hashCode() must…
- On a typical 64-bit compiler (8-byte pointers, 4-byte int, natural alignment), what does sizeof(P) print? cpp class P { int id; public…
- What is printed? java class P { static { System.out.print("1"); } { System.out.print("2"); } P() { System.out.print("3"); } } class C…
- What is printed? java class P { P() { show(); } void show() { } } class C extends P { final int a = 5; int b = 7; final String s = "s"…
- What is printed? java // static methods of the main class: static int f() { int x = 1; try { x = 2; throw new IllegalStateException(); }…