7

假设我有以下内容:

List<Apple> myList = new ArrayList<Apple>();

如果我想调用myList.add(myApple),Java 期望 frommyApple具有类型Apple,而不是任何其他类型(当然子类除外)。但是,如果我想要一个对象 ( Blender) 并根据内部声明的类型具有不同的方法签名<>并且没有方法重载怎么办?像这样:

Blender<Apple> Tool = new Blender<Apple>();
Tool.blendIt(new Apple()); //expects to have only apples in here

Blender<Banana> OtherTool = new Blender<Banana>();
OtherTool.blendIt(new Banana()); //only Banana's are permitted

可能吗?

4

3 回答 3

11

您正在寻找通用类

class Blender<T>{
T t;
public void blendIt(T arg){
//stuff
}
}

class Test {
   public void method() {
     Blender<Apple> blendedApple = new Blender<Apple>();
     blendedApple.blendIt(new Apple()); 
     Blender<Bannana> blendedBannana = new Blender<Bannana>();     
     blendedBannana.blendIt(new Bannana());
   }
 }
于 2013-02-15T18:59:42.120 回答
2

是的:

public class Blender<T> {
   public void blendIt(T arg) { ... }
}
于 2013-02-15T19:00:32.330 回答
1

In Java generics are NOT just for Collections only. It is a general concept and applies to classes, methods, etc. You can create a generic class.

于 2013-02-15T19:07:26.797 回答