1

Is there a way with Java generics to tell the compiler that type T must be of type U? E.g.

public class Whatever<T, U> {

    T specific;
    U moreGeneral;

}

Now, I want to ensure that T is a subclass of U. Is there a way to specify this?

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
jwl
  • 10,268
  • 14
  • 53
  • 91

2 Answers2

8

Simply use

public class Whatever<T extends U,U>
Dici
  • 25,226
  • 7
  • 41
  • 82
  • This won't work. This will throw illegal forward reference to U. – kuriouscoder Dec 19 '14 at 23:34
  • I thought so (first answered reversing the order), but just tried, and it works. Try by yourself, it compiles both ways (used JDK 8) – Dici Dec 19 '14 at 23:35
  • 2
    @kuriouscoder 1.5? Haven't you found an older version? :D – Tom Dec 19 '14 at 23:40
  • Beats me. Now I am digging the release on when it was fixed. Incidentally, I happened to be on a machine with an older one. – kuriouscoder Dec 19 '14 at 23:41
  • @kuriouscoder Also works with JDK 7, so look at the changelog of JDK 6 it should be there – Dici Dec 19 '14 at 23:43
  • 2
    There is another post related to this: http://stackoverflow.com/questions/13501836/possible-java-compiler-bug-program-does-not-compile-with-some-compilers and http://stackoverflow.com/questions/5201687/forward-reference-of-type-parameter-in-java-generics Apparently, it was fixed in JDK 1.7 – kuriouscoder Dec 19 '14 at 23:48
4

To clarify, the following would do the trick on JDK pre 1.7. When trying to switch the order of declaration of U and T I get illegal forward reference to type argument U. As in other posts, it doesn't seem to be an issue with newer JDK versions.

As per this post this was fixed in JDK 1.7

public class Whatever <U, T extends U> {
    T specific;
    U moreGeneral;
}
Community
  • 1
  • 1
kuriouscoder
  • 5,394
  • 7
  • 26
  • 40