Java泛型和接口 [英] Java Generics and interfaces

查看:124
本文介绍了Java泛型和接口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有这样的设计:

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

class FooImpl实现Foo< Integer> {
// code ...
}

接口Bar扩展Foo {
//代码...
}

class BarImpl extends FooImpl implements Bar {
// code ...
}



它给了我编译错误:


接口Foo不能

不同参数:Foo和
Foo


这个问题的一个简单解决方法是:

 界面栏扩展Foo<整数> {b $ b // code ... 
}

Bar接口中的整数类型是完全没用的。

有没有更好的方法可以解决这个问题?
有什么更好的设计?



感谢您的建议。
$ b 编辑:

给出的解决方案:

 >界面栏< T>延伸Foo< T> 

没问题,但它与我以前的解决方案相同。我不需要T型酒吧。



让我举个更好的例子:

 接口ReadOnlyEntity {
}

接口ReadWriteEntity扩展ReadOnlyEntity {
}
$ b $接口ReadOnlyDAO< T扩展ReadOnlyEntity> {
}

接口ReadWriteDAO< K扩展ReadWriteEntity,T扩展ReadonlyEntity>扩展ReadOnlyDAO< T> {
}

这是一个很好的设计吗?

解决方案

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



编辑:


这是一个很好的设计吗?



不,在我看来。


Having this design :

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...
}

It gives me Compile Error :

The interface Foo cannot be implemented more than once with different arguments: Foo and Foo

a simple fix for this issue is :

interface Bar extends Foo<Integer> {
 // code...
}

Integer type in Bar interface is totally useless.

is there any better way to solve this issue ? any better design?

Thanks for your advices.

EDIT:

given solution:

> interface Bar<T> extends Foo<T> 

is ok, but its same as my previous solution. i don't need T type in Bar.

let me give a better sample:

interface ReadOnlyEntity {
}

interface ReadWriteEntity extends ReadOnlyEntity {
}

interface ReadOnlyDAO<T extends ReadOnlyEntity> {
}

interface ReadWriteDAO<K extends ReadWriteEntity, T extends ReadonlyEntity> extends ReadOnlyDAO<T> {
}

is this a good design?

解决方案

I'd recommend thinking of a type for the Bar generic or rethink your design. If there's no object that makes sense for Bar, then it shouldn't be implementing Foo<T>.

EDIT:

is this a good design?

No, not in my opinion.

这篇关于Java泛型和接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆