OCP Stage 2 Problem 1.21 – Explanation

Given the following two files:

package doomed;
public class Doom {
    protected int level;
    int frags;

package doomed;
public class Player {
    public static void main(String[] args) {
        Doom session = new Doom();
        session.level++;                 // n1
        session.frags += 1000;           // n2
        System.out.println(session.level + " - " + session.frags);

What is the result?

A. 1 – 1000
B. 0 – 0
C. RuntimeException is thrown at line n1.
D. RuntimeException is thrown at line n2.
E. Compilation fails.


The correct answer is A.


The code compiles because the protected field level is accessible to Player since both classes belong to the same package. On the other hand, if Player were declared in a different package, the code would’ve thrown a comperr.

Speaking of runtime exceptions, the code does not contain unexpected arguments or generate unexpected results, so the fields will be successfully incremented.



As soon as you see a package declaration and the protected modifier, check the class members’ visibility.


Java Class Design

Implement inheritance including visibility modifiers and composition

Leave Comment

Your email address will not be published.