Java泛型和接口

mhs*_*ams 4 java generics

有这个设计:

interface Foo<T> {
   void doSomething(T t);
}

class FooImpl implements Foo<Integer> {
   //code... 
}

interface Bar extends Foo {
   //code...
}

class BarImpl extends FooImpl implements Bar {
     //code...
}
Run Code Online (Sandbox Code Playgroud)

它给了我编译错误:

接口Foo不能用不同的参数实现多次:Foo和Foo

解决此问题的简单方法是:

interface Bar extends Foo<Integer> {
 // code...
}
Run Code Online (Sandbox Code Playgroud)

Bar界面中的整数类型完全没用.

有没有更好的方法来解决这个问题?任何更好的设计?

谢谢你的建议.

编辑:

给定解决方案

> interface Bar<T> extends Foo<T> 
Run Code Online (Sandbox Code Playgroud)

没关系,但和我之前的解决方案一样.我在Bar中不需要T型.

让我给出一个更好的样本:

interface ReadOnlyEntity {
}

interface ReadWriteEntity extends ReadOnlyEntity {
}

interface ReadOnlyDAO<T extends ReadOnlyEntity> {
}

interface ReadWriteDAO<K extends ReadWriteEntity, T extends ReadonlyEntity> extends ReadOnlyDAO<T> {
}
Run Code Online (Sandbox Code Playgroud)

这是一个很好的设计吗?

duf*_*ymo 5

我建议考虑Bar泛型的类型或重新考虑你的设计.如果没有对Bar有意义的对象,那么它就不应该实现Foo<T>.

编辑:

这是一个很好的设计吗?

不,不在我看来.