If you always want the type T
to implement Comparable
you can enforce this as follows.
public class C<T extends Comparable<? super T>> {
public C() {
}
}
This is better than throwing an exception at runtime. It will not even compile if someone tries to write new C<some non-Comparable type>()
. Note that Comparable
is a generic type, so it should not be used without type parameters; it should not simply be
public class C<T extends Comparable>
If the type T
will not always implement Comparable
, but you want a specific constructor that will only work for Comparable
types, then the answer is that you can't do this with constructors, but you can do it with a static method.
public class C<T> {
public C() {
// Constructor that works with any T
}
public static <T extends Comparable<? super T>> C<T> getNew() {
C<T> c = new C<>();
// Do stuff that depends on T being Comparable
return c;
}
}