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;

  1. A. Only (3)
  2. B. Only (1) and (2)
  3. C. All three
  4. 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

Exams that ask this topic