2016-05-13 51 views
2

我在我的域模型以下實體:Java的通用上界通配符錯誤

class Point { 
    public String details; 

    public Point() { 
     details = "empty"; 
    } 

    public Point(String details) { 
     this.details = details; 
    } 
} 

class BasicPoint<X, Y> extends Point { 
    public X x; 
    public Y y; 

    public BasicPoint() {} 

    public BasicPoint(X x, Y y) { 
     this.x = x; 
     this.y = y; 
    } 
} 

class Collector<T> { 
    T elem; 

    public void collect(T elem) { 
     this.elem = elem; 
    } 
} 

我想對數據應用操作,並返回數據點或BasicPoint,如上聲明,但編譯器用下面的錯誤雖然OUT抱怨延伸點:

class Operator<OUT extends Point> { 
    public Collector<OUT> operate(Collector<OUT> collector) { 

     // compile error, collect(OUT) cannot be applied to BasicPoint<Integer, Integer> 
     collector.collect(new BasicPoint<Integer, Integer>(1,2)); 

     return collector; 
    } 
} 

主要方法應該是這樣的:

Collector<BasicPoint<Integer, Integer>> c = new Collector<>(); 
c = new Operator<BasicPoint<Integer, Integer>>().operate(c); 
System.out.println(c.elem.getClass() == new BasicPoint<Integer, Integer>().getClass()); 
+0

你有代碼,打開IDE並生成輸出。 – user1933888

+0

問題是代碼不能編譯,它在問題 – zequihg50

+0

中定義的Operator類中顯示一個錯誤什麼是編譯器錯誤呢? –

回答

2

您的Operator是通用的,它不能在BasicPoint上應用collect,只有OUT。你可以讓你Collector摘要:

abstract class Operator<OUT extends Point> { 
    abstract Collector <OUT> operate(Collector<OUT> collector); 
} 

然後一個BasicPointOperator將包含要實際執行:

class BasicPointOperator extends Operator<BasicPoint<Integer, Integer>> { 

    @Override 
    Collector<BasicPoint<Integer, Integer>> operate(Collector<BasicPoint<Integer, Integer>> collector) { 
     collector.collect(new BasicPoint<Integer, Integer>(1,2)); 
     return collector; 
    } 
} 

PointOperator,這是一個比較通用的

class PointOperator extends Operator<Point> { 

    @Override 
    Collector<Point> operate(Collector<Point> collector) { 
     collector.collect(new BasicPoint<Integer, Integer>(1,2)); 
     return collector; 
    } 
} 
+0

Afaik it_could_ work的方式,他首先編程它,你知道_why_ it劑量工作?我想編譯器只是忽略'Operator'中的'OUT'類型。 – hinneLinks

+1

它不起作用,因爲'BasicPoint'不是'OUT'類型。他們只有一個共同的祖先'點'。 –

1

問題是你不能把東西置於,除非類型參數是contravariant。類似的東西

public Collector<?> operate(Collector<? super Point> collector) { 
    collector.collect(new BasicPoint<Integer, Integer>(1,2)); 
    collector.collect(new Point()); 

    return collector; 
}