Java OCA OCP Practice Question 1516

Question

What is the output of the following application?

package race; //  ww  w  .ja v  a 2s. c om
  
interface Mark1 { 
   int SPEED = 5; 
   default int getSpeed() { return SPEED; } 
} 
interface Mark2 { 
   int MAX_SPEED = 5; 
   default int getSpeed() { return MAX_SPEED; } 
} 
public class Main implements Mark1, Mark2 { 
   public static void main(String[] argv) { 
      class MyClass extends Main { 
         @Override public int getSpeed() { return 10; } 
      }; 
      System.out.print(new MyClass().getSpeed()); 
   } 
} 
A.   5
B.   10
C.   The code does not compile due to the definition of Racecar.
D.   The code does not compile for some other reason.


D.

Note

Both the Mark1 and Mark2 interfaces define a default method getSpeed() with the same signature.

In fact, both getSpeed() methods return the same value of 5.

The class Main implements both interfaces, which means it inherits both default methods.

Since the compiler does not know which one to choose, the code does not compile, and the answer is Option D.

If the Main class had overridden the getSpeed() method, then the code would have compiled without issue and printed 10 at runtime.

The local class Racecar defined in the main() method compiles without issue, making Option C incorrect.




PreviousNext

Related