Java OCA OCP Practice Question 1533

Question

What is the output of the following application?

1:  package mypkg; 
2: /*w  w w . j  av a 2 s. c o m*/
3:  interface Printable { void print(); } 
4:  public class Main { 
5:     public static void main(String[] food) { 
6:        Printable apple = new Printable() { 
7:           @Override 
8:           void print() { 
9:              System.out.print("Yummy!"); 
10:          } 
11:       } 
12:    } 
13: } 
  • A. The application completes without printing anything.
  • B. Yummy!
  • C. One line of this application fails to compile.
  • D. Two lines of this application fail to compile.


D.

Note

This application declares an anonymous inner class that implements the Printable interface.

Interface methods are public, whereas the override in the anonymous inner class uses package-private access.

Since this reduces the visibility of the method, the declaration of print() on line 8 does not compile.

Next, the declaration of the apple object must end with a semicolon (;) on line 11, and it does not.

The code does not compile, and Option D is the correct answer.

If these two issues were corrected, with the public modifier and missing semi-colon ( ;), then the correct answer would be Option A because the code does not actually call the print() method; it just declares it.




PreviousNext

Related