2012-12-04 68 views
1

我想弄清楚爲什麼以下在Java中似乎不起作用。非法在java構造函數中有抽象類列表?

這裏是基本的抽象類:

public abstract class Shape { 

} 

可以說,它有兩個具體的類,圈:

public class Circle extends Shape { 

} 

和廣場,其中有多個構造函數:

public class Square extends Shape { 

public Square(Shape shape) 
{ 
    // nothing 
} 

public Square(List<Shape> shapes) 
{ 
    // nothing 
} 
} 

鑑於此代碼:

Circle c = new Circle(); 
List<Circle> cList = new ArrayList<Circle>(); 
Square s = new Square(c); 
Square s2 = new Square(cList); 

最後一行產生錯誤:

The constructor Square(List<Circle>) is undefined. 

但我在廣場更是把參數List<Shape>的構造函數,圓是一種形狀 - 這需要一個單一的外形是精細的構造。所以我不明白爲什麼我會得到這個錯誤。謝謝你的幫助。

回答

5

定義構造函數爲:

 public Square(List<? extends Shape> shapes) 
     { 
      // nothing 
     } 

這意味着它接受延長Shape所有類。

預防性注意事項:請注意由於相同的事實產生的副作用,即它接受所有延伸Shape的類別。

+0

感謝您的快速響應!我一直在使用Java幾個月,但之前還沒有看到通配符類型參數。 – JasonK

0

But I have the constructor in Square which takes the parameter List, and Circle is a Shape - the constructor that takes a single Shape is fine.

這是因爲泛型類型在Java中是不變的。我們知道Circle is-a Shape,但仍然List<Circle>不是-,所以您不能用List<Circle>替換List<Shape>。爲了填補這個空白,你必須使用@Yogendra指出的有界通配符。

你可以找到一個解釋here