Java OCA OCP Practice Question 1389

Question

Given the application below, which lines do not compile? (Choose three.)

package mypkg; /*from   w w  w  .ja va  2s  .c om*/
interface Pet { 
   protected String getName();  // h1 
} 
class Cat implements Pet { 
   String getName() {  // h2 
      return "Kitty"; 
   } 
} 
public class Main implements Pet { 
   String getName() throws RuntimeException {  // h3 
      return "Maingy"; 
   } 
   public static void main(String[] adoption) { 
      Pet friend = new Main();  // h4 
      System.out.print(((Cat)friend).getName());  // h5 
      System.out.print(((Main)null).getName());  // h6 
   } 
} 
  • A. Line h1
  • B. Line h2
  • C. Line h3
  • D. Line h4
  • E. Line h5
  • F. Line h6


A, B, C.

Note

All of the compilation issues with this code involve access modifiers.

First, all interface methods are implicitly public, and explicitly setting an interface method to protected causes a compilation error on line h1, making Option A correct.

Next, lines h2 and h3 both override the interface method with the package-private access modifier.

Since this reduces the implied visibility of public, the overrides are invalid and neither line compiles.

Options B and C are also correct.

The RuntimeException is allowed in an overridden method even though it is not in the parent method signature because only new checked exceptions in overridden methods cause compilation errors.

Line h4 is valid.

An object can be implicitly cast to a superclass or inherited interface.

Lines h5 and h6 will compile without issue but independently throw a ClassCastException and a NullPointerException at runtime, respectively.

Since the question only asks about compilation problems, neither of these are correct answers.




PreviousNext

Related