Java OCA OCP Practice Question 1593

Question

Which line in the main() method doesn't compile or points to a class that doesn't compile?

1:   interface Drawable<C> {
2:      void draw(C c);
3:   }/*w w  w  .  ja va  2s  .c om*/
4:   class Log<C> implements Drawable<C> {
5:      public void draw(C c) {
6:         System.out.println(c);
7:      }
8:   }
9:   class Email implements Drawable<Main> {
10:     public void draw(Main c) {
11:        System.out.println(c);
12:     }
13:  }
14:  class File implements Drawable<Main> {
15:     public void draw(C c) {
16:        System.out.println(c);
17:     }
18:  }
19:  public class Main {
20:     public static void main(String[] args) {
21:       Drawable<Main> c1 = c -> System.out.println(c);
22:       Drawable<Main> c2 = new Log<>();
23:       Drawable<Main> c3 = new Email();
24:       Drawable<Main> c4 = new File();
25:     }
26:  }
  • A. Line 21
  • B. Line 22
  • C. Line 23
  • D. Line 24


D.

Note

The Drawable interface declares a formal type parameter.

This means that a class implementing it needs to specify this type.

The code on line 21 compiles because the lambda reference supplies the necessary context making Option A incorrect.

Option B declares a generic class.

While this doesn't tell us the type is Main, it punts the problem to the caller of the class.

The declaration of c2 on line 22 compiles because it supplies the type, making Option B incorrect.

The code on line 23 compiles because the Email itself supplies the type making Option C incorrect.

Option D has a problem.

Email and File appear similar.

However, File refers to C.

This type parameter exists in the interface.

It isn't available in the class because the class has said it is using Main as the type.

Since the File class itself doesn't compile, the line with c4 can't instantiate it, and Option D is the answer.




PreviousNext

Related