Java OCA OCP Practice Question 10

Question

Given the following class:

package mypkg; 
public class Fish { 
     protected int size; 
     protected void swim() { } 
} 

Which of the following may appear in a subclass of Fish named Tuna that is not in the mypkg package?

  • A. void swim() { }
  • B. public void swim() { }
  • C. size = 12;
  • D. (new Tuna()).size = 12;


B, C.

Note

A is illegal because it attempts to override the swim() method with a more restricted access mode.

B overrides with a less-restricted access mode, which is legal.

C is legal because it accesses protected superclass data of the current instance.

D is illegal because it accesses protected superclass data of a different instance.




PreviousNext

Related