如何在java中继续使用泛型
我有一个接口
public interface Doable<T,U> {
public U doStuff(T t);
}
我有一个实现 Doable
的抽象类
public abstract class AbstractDoable<T,U> implements Doable<T, U> {
private SomeClass someClass;
}
现在我需要实现上述类,但我需要为 T
使用不同的类U
。
请建议我应该如何继续,因为我需要使用不同的 T
和 U
来实现 AbstractDoable
。例如:
ConvertDoable<String,Integer> extends AbstractDoable
或
ConvertDoable<A,B> extends AbstractDoable
I have a interface
public interface Doable<T,U> {
public U doStuff(T t);
}
I have an abstract class which implements Doable<T,U>
public abstract class AbstractDoable<T,U> implements Doable<T, U> {
private SomeClass someClass;
}
Now I need to implement the above classes, but I need to use different classes for T
and U
.
Please suggest how should I proceed in this as I will need to have multiple implemetations of AbstractDoable
with different T
and U
. For example:
ConvertDoable<String,Integer> extends AbstractDoable
or
ConvertDoable<A,B> extends AbstractDoable
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您可以创建您想要的
Doable
或AbstractDoable
的任何子类。例如:或者
我不确定您的
someClass
成员在AbstractDoable
中的用途是什么。你能解释一下它的用途吗?You can create whatever subclasses of
Doable
orAbstractDoable
you want. For example:or
I'm not sure what the purpose of your
someClass
member is inAbstractDoable
. Can you explain what it is for?如果您担心类膨胀,请考虑匿名类 - 根据需要“动态”定义的类:
If you're worried about class bloat, consider anonymous classes - classes defined "on the fly" as you need them:
您的具体实现应该在
AbstractDoable
上指定类型,或者继续传递参数化泛型:
Your concrete implementations should either specify the types on
AbstractDoable
or continue to pass along parameterized generics:
关于泛型的整个想法是,您创建一个支持所有类型的类(或至少支持从类继承或实现接口的所有类)的单个类。
You之间没有区别,
同样在Java(字节码)中,say和
因此您需要定义一个类来处理可能提供给它的所有不同对象。
The whole idea about generics is that you make a single class which supports all types of classes (or at least all classes who inherit from a class or implement an interface).
Also in Java (bytecode) there is no difference between say
and
You thus need to define a single class that can handle all the different objects that might be given to it.