我想弄清楚为什么以下内容在 Java 中似乎不起作用。
这是基本的抽象类:
public abstract class Shape {
}
假设它有两个具体类,Circle:
public class Circle extends Shape {
}
和 Square,它有多个构造函数:
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.
但是我在 Square 中有一个构造函数,它接受参数 List<Shape>
,而 Circle 是一个 Shape - 采用单个 Shape 的构造函数就可以了。所以我不明白为什么我会收到这个错误。感谢您的帮助。
最佳答案
将构造函数定义为:
public Square(List<? extends Shape> shapes)
{
// nothing
}
这意味着它接受所有扩展 Shape
的类。
注意事项:请注意由于相同事实而产生的副作用,即它接受所有扩展 Shape
的类。
关于java - 在java构造函数中有抽象类列表是非法的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13694066/