我遇到了构造函数的问题。
public abstract class ShapeDrawer implements iShapeDrawer {
protected SimpleLine line; // the line to be drawn
protected SimpleOval oval; // the oval to be drawn
protected SimpleTriangle triangle; // the triangle to be drawn
protected SimplePolygon rectangle; // the triangle to be drawn
public ShapeDrawer(SimpleLine line) {
this.line = line;
}
public ShapeDrawer(SimpleOval oval) {
this.oval = oval;
}
public ShapeDrawer(SimpleTriangle triangle) {
this.triangle = triangle;
}
public ShapeDrawer(SimplePolygon rectangle) {
this.rectangle = rectangle;
}
}
当我尝试运行时,它会转到第一个构造函数,并为每个构造函数抛出错误。
错误:不兼容的类型:SimpleOval无法转换为SimpleLine 超级(椭圆形);
这是来自Oval类
的一点public class OvalDrawer extends ShapeDrawer implements iShapeDrawer{
public OvalDrawer(SimpleOval oval) {
super(oval);
}
}
我有SimpleShape类,它是SimpleOval,SimpleLine等的父类,并且具有所有方法。 SimpleOval的示例
public class SimpleOval extends SimpleShape {
public SimpleOval(int xStart, int yStart, int xEnd, int yEnd, Color colour, int thickness, ShapeType shapeType) {
super(xStart, yStart, xEnd, yEnd, colour, thickness, shapeType);
}
有什么建议吗?
答案 0 :(得分:5)
我建议使ShapeDrawer
泛型,使用类型参数某些Shape
的子类:
public abstract class ShapeDrawer<T extends Shape> implements iShapeDrawer {
protected T shape; //the shape to be drawn
public ShapeDrawer(T shape) {
this.shape = shape;
}
}
然后,每个不同的形状将具有相应的ShapeDrawer
类。例如,SimpleOval
将绘制为:
public class SimpleOvalDrawer extends ShapeDrawer<SimpleOval> {
public SimpleOvalDrawer(SimpleOval oval) {
super(oval);
}
}
应为其他Shape
子类型引入类似的类。
还没有SimpleOvalDrawer
明确实现iShapeDrawer
界面,因为ShapeDrawer
已经这样做了。