Java几个构造函数,每个构造函数有一个参数和不同的类型

时间:2016-03-14 15:25:11

标签: java

我遇到了构造函数的问题。

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);   
}

有什么建议吗?

1 个答案:

答案 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已经这样做了。