簡體   English   中英

泛型/接口方法不適用

[英]generics / interface method not applicable

我有一個蔬菜接口,例如,蘋果,胡蘿卜...然后有一個通用類型的類收集器,它們可以是花椰菜,胡蘿卜等的收集器...我需要實現一個函數來給一個收藏家到另一個,問題是,如果我嘗試使用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;
    }
}

一個例子:我添加了take and drop代碼

和一個例子:

Collector<Carrot> carrotCollector1 = new Collector<Carrot>("carrot-collector-1");
Collector<Vegetable> vegetableCollector = new Collector<Vegetable>("vegetable-collector");
carrotCollector1.giveTo(vegetableCollector);

那就是我得到的錯誤:

類型Collector中的方法GiveTo(Collector)不適用於參數(Collector)

正確的方法是將您的方法更改為:

public void giveTo(Collector<? super T> other) throws AlreadyCarryingException {
   // ... omitted some code  
   other.take(drop());
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM