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

Ant*_*jke 2 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;
    }
}
Run Code Online (Sandbox Code Playgroud)

当我试图运行时,它会转到第一个构造函数,并为每个构造函数抛出错误.

错误:不兼容的类型:SimpleOval无法转换为SimpleLine super(椭圆形);

这就是来自Oval课程的一点

public class OvalDrawer extends ShapeDrawer implements iShapeDrawer{

    public OvalDrawer(SimpleOval oval) {
        super(oval);
    }
}
Run Code Online (Sandbox Code Playgroud)

我有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);   
}
Run Code Online (Sandbox Code Playgroud)

有什么建议?

Kon*_*kov 5

我建议ShapeDrawer使用type-parameter做一些子类的泛型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;
    }
}
Run Code Online (Sandbox Code Playgroud)

然后,每个不同的形状将具有相应的ShapeDrawer类.例如,SimpleOval将使用以下内容绘制:

public class SimpleOvalDrawer extends ShapeDrawer<SimpleOval> {
    public SimpleOvalDrawer(SimpleOval oval) {
        super(oval);
    }
}
Run Code Online (Sandbox Code Playgroud)

应该为其他Shape子类型引入类似的类.

也没有必要像现在SimpleOvalDrawer这样明确地实现iShapeDrawer接口ShapeDrawer.