Extending both T and SomeInterface<T> in Java
Asked Answered
C

2

8

I want to create a class that takes two parameters. One should be typed simply as T. The other should be typed as something that extends both T and SomeInterface<T>. When I attempt this with

public class SomeClass<T, S extends SomeInterface<T> & T>

then Java complains with

"The type T is not an interface; it cannot be specified as a bounded parameter"

and if instead I attempt to create an interface for S with

public interface TandSomeInterface<T> extends SomeInterface<T>, T

then Java complains with

"Cannot refer to the type parameter T as a supertype"

Is there any way to do this in Java? I think you can do it in C++...?

Caiman answered 30/3, 2010 at 7:46 Comment(2)
Note that C++ templates are a lot more powerful than Java generics. Just because it can be done in C++, doesn't mean it can be done in Java.Prader
related: https://mcmap.net/q/327649/-java-generics-make-generic-to-extends-2-interfacesHygienics
G
3

You can't create an interface that extends the type parameter T since there's no contract that would guarantee T to be an interface. And of course interface extending a class is not allowed.

Goglet answered 30/3, 2010 at 8:28 Comment(1)
But is there any way to circumvent this to get the same effect?Caiman
L
3

this works if you extend an interface as well:

public class SomeClass<T extends I, S extends SomeInterface<T> & I>

but maybe it's not exactly what you want ...

Laicize answered 30/3, 2010 at 8:57 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.