2012-12-04 69 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