Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Double generic constraint on class in Java: extends ConcreteClass & I

Is there a way to define a generic constraint in Java which would be analogous to the following C# generic constratint ?

class Class1<I,T> where I : Interface1, Class2 : I

I'm trying to do it like this:

class Class1<I extends Interface1, T extends I & Class2>

But the compiler complains about the "Class2" part: Type parameter cannot be followed by other bounds.

like image 416
axk Avatar asked Sep 25 '08 09:09

axk


2 Answers

The simplest way I can see of resolving the Java code is to make Class2 an interface.

You cannot constrain a type parameter to extends more than one class or type parameter. Further, you can't use super here.

like image 168
Tom Hawtin - tackline Avatar answered Oct 18 '22 17:10

Tom Hawtin - tackline


This code compiles here fine:

interface Interface1 {}

class Class2 {}

class Class1<I extends Interface1, T extends Class2 & Interface1> {}

Why do you need the I type there when you assume only Interface1 anyway? (you won't know anything more in your class about I than it extends Interface1)

like image 36
mitchnull Avatar answered Oct 18 '22 18:10

mitchnull