Java OCA OCP Practice Question 1333

Question

Given that Integer and Long are subclasses of Number,

what type can be used to fill in the?blank in the class below to allow it to compile?

package mypkg; // w ww. ja  va  2 s  . c om

interface TV { public Number play(); } 

abstract class Movie { public Long play() {return 3L;} } 

public class Stream extends Movie implements TV { 
   public ___ play() { 
      return 12; 
   } 
} 
  • A. Long
  • B. Integer
  • C. Long or Integer
  • D. Long or Number


A.

Note

The play() method is overridden in Stream for both TV and Movie, so the return type must be covariant with both.

Long is a subclass of Number, and therefore, it is covariant with the version in TV.

Since it matches the type in Movie, it can be inserted into the blank and the code would compile.

While Integer is a subclass of Number, meaning the override for TV is valid, it is not a subclass of Long used in Movie.

Using Integer would cause the code to not compile.

Number is compatible with the version of the method in TV but not with the version in Movie, because Number is a superclass of Long, not a subclass.

Long is the only class that allows the code to compile.

Option A is the correct answer.




PreviousNext

Related