Java OCA OCP Practice Question 2295

Question

Which occurrences of the type parameter T are illegal?

public class Box<T> {
  private T item;                                      // (1)
  private static T[] storage = new T[100];              // (2)

  public Box(T item) { this.item = item; }             // (3)

  public T getItem() { return item; }                  // (4)
  public void setItem(T newItem) { item = newItem; }   // (5)

  public static void getAllItems(T newItem) {           // (6)
    T temp;                                            // (7)
  }//from   w  ww  . j  a  v a  2 s . c  o  m
}

Select the three correct answers.

  • (a) Occurrence of the type parameter T in (1).
  • (b) Occurrences of the type parameter T in (2).
  • (c) Occurrence of the type parameter T in (3).
  • (d) Occurrence of the type parameter T in (4).
  • (e) Occurrence of the type parameter T in (5).
  • (f) Occurrence of the type parameter T in (6).
  • (g) Occurrence of the type parameter T in (7).


(b), (f), and (g)

Note

We cannot refer to the type parameters of a generic class in a static context.

In static initializer blocks, static field declarations, and as types of local variables in static methods.

Also we cannot create an array of a type parameter, as in (2).




PreviousNext

Related