Java OCA OCP Practice Question 1023

Question

What is the output of the following code?

1: interface Checkable { 
2:   default boolean check() { return true; } 
3: } //from  www  .  jav  a2  s.  co  m
4: public class Main implements Checkable { 
5:   public boolean check() { return false; } 
6:     public static void main(String[] args) { 
7:     Checkable nocturnal = (Checkable)new Main(); 
8:     System.out.println(nocturnal.check()); 
9:     } 
10: } 
  • A. true
  • B. false
  • C. The code will not compile because of line 2.
  • D. The code will not compile because of line 5.
  • E. The code will not compile because of line 7.
  • F. The code will not compile because of line 8.


B.

Note

This code compiles and runs without issue, outputting false, so option B is the correct answer.

The first declaration of check() is as a default interface method, assumed public.

The second declaration of check() correctly overrides the default interface method.

Finally, the newly created Main instance may be automatically cast to a Checkable reference without an explicit cast, although adding it doesn't break the code.




PreviousNext

Related