Java OCA OCP Practice Question 1607

Question

Which option cannot fill in the blank to print Clean socks?

class Logger<T> {
   T item;//from  ww  w  . j a  v a 2s.  c  om
   public void clean(T item) {
      System.out.println("Clean " + item);
   }
}
public class Main {
   public static void main(String[] args) {
      _____
      log.clean("socks");
   }
}
  • A. Logger log = new Logger();
  • B. Logger log = new Logger<String>();
  • C. Logger<String> log = new Logger<>();
  • D. All three can fill in the blank.


D.

Note

The Logger class takes a formal type parameter named T.

Option C shows the best way to call it.

This option declares a generic reference type that specifies the type is String.

It also uses the diamond syntax to avoid redundantly specifying the type on the right-hand side of the assignment.

Options A and B show that you can omit the generic type in the reference and still have the code compile.

You do get a compiler warning scolding you for having a raw type.

But compiler warnings do not prevent compilation.

With the raw type, the compiler treats T as if it is of type Object.

That is OK in this example because the only method we call is toString() implicitly when printing the value.

Since toString() is defined on the Object class, we are safe, and Options A and B work.

Since all three can fill in the blank, Option D is the answer.




PreviousNext

Related