开发者

Is it possible to simultaneously and generically subclass both a bounded generic class and a generic interface?

开发者 https://www.devze.com 2022-12-21 20:06 出处:网络
I\'m trying to create a new class by subclassing another generic class (with a bound) and implementing a generic interface (without a bound):

I'm trying to create a new class by subclassing another generic class (with a bound) and implementing a generic interface (without a bound):

public class Foo1<T extends Bar> {
    ...
}

public interface Foo2<T> {
    ...
}

public class ProblemClass<T extends Bar, U> 
        extends Foo1<T extends Bar> implements Foo2<U> {
    ...
}

This gives me compile errors. I also tried:

public class ProblemClass<T, U> 
        extends Foo1<T extends Bar> implements Foo2<U> {
    .开发者_StackOverflow..
}

public class ProblemClass<T extends Bar, U> 
        extends Foo1<T> implements Foo2<U> {
    ...
}

But neither of these work either.

What's the correct syntax to define my subclass in a way that lets me keep the typing generic, letting me pass they types along to the superclass and interface? Is this even possible?

Thanks!


This declaration should work fine. What error do you get? What compiler are you using?

class ProblemClass<T extends Bar, U>
  extends Foo1<T>
  implements Foo2<U>
{
  ...
}

This is valid Java. If IDEA's compiler rejects it, IntelliJ has a bug.


From the code you posted, you only have class Foo not Foo1. Is that the reason? or just posting-edit error?

I think this should work

public class ProblemClass<T extends Bar, U> 
        extends Foo1<T> implements Foo2<U> {
    ...
}


This gives no compile errors with JDK 1.6.0_07

public class Bar {}

public class Foo1<T extends Bar> {}

public interface Foo2<T> {}

public class ProblemClass<T extends Bar, U> extends Foo1<T> implements Foo2<U> {}


This (from your question):

public class ProblemClass<T extends Bar, U> 
        extends Foo1<T extends Bar> implements Foo2<U> {
    ...
}

should be this:

public class ProblemClass<T extends Bar, U> 
        extends Foo1<T> implements Foo2<U> {
    ...
}

That is, you should not restate the bounds when extending Foo1.

With that correction the code compiles fine in javac. If IntelliJ IDEA still refuses to compile it then you may have found a bug, or perhaps the "Bar" you're referring to in Foo.java is not the same "Bar" in ProblemClass.java?

0

精彩评论

暂无评论...
验证码 换一张
取 消