Java OCA OCP Practice Question 1397

Question

Given that FileNotFoundException is a subclass of IOException and Long is a subclass of Number, what is the output of the following application?

package materials; 
? 
import java.io.*; 
? 
class Shape { 
    protected long count; 
    public abstract Number getCount() throws IOException;  // q1 
    public Shape(int count) { this.count = count; } 
} 
public class Main extends Shape { 
   public Main() { super(15); } 
   public Long getCount() throws FileNotFoundException {  // q2 
      return count; 
   } /* ww w  .j  a  v  a2s  .  c o  m*/
   public static void main(String[] cost) { 
      try { 
         final Shape ring = new Main();  // q3 
         System.out.print(ring.getCount());  // q4 
      } catch (IOException e) { 
         e.printStackTrace(); 
      } 
   } 
} 
  • A. 15
  • B. It does not compile because of line q1.
  • C. It does not compile because of line q2.
  • D. It does not compile because of line q3.
  • E. It does not compile because of line q4.
  • F. It compiles but throws an exception at runtime.


B.

Note

This problem appears to be to be about overriding a method, but in fact, it is much simpler.

The class Shape is not declared abstract, yet it includes an abstract method.

To fix it, the definition of Shape would have to be changed to be an abstract class, or the abstract modifier would need to be removed from getCount() in Shape and a method body added.

Since the only answer choice available is to change the getCount() method on line q1, Option B is the correct answer.

Note that the rest of the application, including the override on line q2, is correct and compiles without issue.

The return types Long and Number are covariant since Number is a superclass of Long.

The exception thrown in the subclass method is narrower, so no compilation error occurs on q2.




PreviousNext

Related