Java OCA OCP Practice Question 3127

Question

Which statements are true about the following code?

class SupC<T> {
  public void set(T t) {/*...*/}       // (1)
  public T get() {return null;}        // (2)
}

class SubC1<M,N> extends SupC<M> {
  public void set(N n) {/*...*/}       // (3)
  public N get() {return null;}        // (4)
}

class SubC2<M,N extends M> extends SupC<M> {
  public void set(N n) {/*...*/}       // (5)
  public N get() {return null;}        // (6)
}

Select the four correct answers.

  • (a) The method at (3) overloads the method at (1).
  • (b) The method at (3) overrides the method at (1).
  • (c) The method at (3) results in a compile-time error.
  • (d) The method at (4) overloads the method at (2).
  • (e) The method at (4) overrides the method at (2).
  • (f) The method at (4) results in a compile-time error.
  • (g) The method at (5) overloads the method at (1).
  • (h) The method at (5) overrides the method at (1).
  • (i) The method at (5) results in a compile-time error.
  • (j) The method at (6) overloads the method at (2).
  • (k) The method at (6) overrides the method at (2).
  • (l) The method at (6) results in a compile-time error.


(c), (f), (i), and (k)

Note

The type parameter N in SubC1 does not parameterize the super type SupC.

The erasure of the signature of (3) is the same as the erasure of the signature of (1), i.e., name clash.

Therefore, of the three alternatives (a), (b), and (c), only (c) is correct.

The type parameter N in SubC1 cannot be guaranteed to be a sub type of the type parameter T in SupC, i.e., incompatible return types for get() methods at (4) and (2).

Also, methods cannot be overloaded if only return types are different.

Therefore, of the three alternatives (d), (e), and (f), only (f) is correct.

The type parameter N in SubC2 is a subtype of the type parameter M which parameterizes the super type SupC.

The erasure of the signature of (5) is still the same as the erasure of the signature of (1), i.e., name clash.

Therefore, of the three alternatives (g), (h), and (i), only (i) is correct.

The type parameter N in SubC1 is a subtype of the type parameter T (through M) in SupC, i.e., covariant return types for the get() methods at (6) and (2), which are overridden.

Therefore, of the three alternatives (j), (k), and (l), only (k) is correct.




PreviousNext

Related