我有一个蔬菜接口,例如苹果,胡萝卜...
然后我有一个通用类型的类收集器,它们可以是花椰菜,胡萝卜等的收集器。
我需要实现一个将一个收集器的携带对象分配给另一个收集器的函数,问题是如果我尝试使用Collector.giveTo(Collector),它不会识别出Apple是从Vegetable扩展而来的。
我尝试使用instanceof来完成此操作,但没有成功
这是我的类Collector的构造函数:
/** define collectors able to collect (and carry) one specific type T of objects
* only one T object can be carried at a time
*/
public class Collector<T> {
private String name;
protected T carriedObject = null;
/**
* Creates a Collector object with a name and no carriedObject (carriedObject = null)
* @param name a String, the name of the Collector
*/
public Collector(String name) {
this.name = name;
this.carriedObject = carriedObject;
}
以及一些使用的方法的代码:
/**
* give the carriedObject to another Collector
* @param other the Collector to give the carriedObject to
* @throws AlreadyCarryingException if the other Collector is already carrying an object
*/
public void giveTo(Collector<T> other) throws AlreadyCarryingException {
if (this instanceof Vegetable && other instanceof Vegetable){
if (other.getCarriedObject() != null){
throw new AlreadyCarryingException("Le collector porte deja un objet");
}
else {
other.take(this.drop());
}
}
/**
* drops the carriedObject setting it to null
*/
public T drop(){
T tmp = this.carriedObject;
this.carriedObject = null;
return tmp;
}
/**
* allows the Collector to take an object and sets it as his carriedObject
* @param object the Object to take
* @throws AlreadyCarryingException if the Collector is already carrying an object
*/
public void take(T object) throws AlreadyCarryingException {
//Collector is already carrying an object
if (this.carriedObject != null) {
throw new AlreadyCarryingException("Le collector porte deja un objet");
}
else{
this.carriedObject = object;
}
}
一个例子 :
我添加了取放代码
和一个例子:
Collector<Carrot> carrotCollector1 = new Collector<Carrot>("carrot-collector-1");
Collector<Vegetable> vegetableCollector = new Collector<Vegetable>("vegetable-collector");
carrotCollector1.giveTo(vegetableCollector);
那就是我得到的错误:
类型Collector中的方法GiveTo(Collector)是
不适用于自变量(收集器)
最佳答案
正确的方法是将您的方法更改为:
public void giveTo(Collector<? super T> other) throws AlreadyCarryingException {
// ... omitted some code
other.take(drop());
}