形状对象不接受输入的坐标

时间:2014-03-30 01:37:20

标签: java

我在一件作业上遇到了问题。我必须制作自己的ShapeCircleRectangle课程。问题是当Point对象输入到圆形和矩形中时,Shape类不会在构造函数中接受它以获得新的形状对象。

因此,当我运行主程序时,圆心和矩形顶角的坐标为空,而不是输入的坐标。

如何让Shape接受点坐标?

(对不起,如果代码/术语错了,我还不熟悉Java)

我的形状类:

public class Shape {
    private int sides;
    private Color colour;
    private Point coordinates;

    public Shape (int sides, Point coordinates, Color colour) {
        this.sides = sides;
        this.colour = colour;
        this.coordinates = coordinates;
    }

My Circle课程:

public class Circle extends Shape {
    private Point center;
    private int radius;

    //constructor for circle class
    public Circle(Point center, int radius, Color c) {
        super(0, center, c);
        this.radius = radius;

我的矩形类:

public class Rectangle extends Shape {

    private int sides = 4;
    private Point topCorner;
    private int width, length;

    //Constructor for rectangle
    public Rectangle(Point topCorner, int width, int length, Color c) {
        super(4, topCorner, c);
        this.width = width;
        this.length = length;
    }

我的主要课程:

    public static void main(String[] args) {
        Point p1 = new Point(0,20);
        Point p2 = new Point(20,0);
        Point p3 = new Point(30,30);

        Shape r = new Rectangle(p1, 10, 15, Color.BLUE);
        Shape c = new Circle (p3, 25, Color.YELLOW);

1 个答案:

答案 0 :(得分:1)

这是因为您从不初始化topCornercenter

Circle构造函数中,添加

this.center = center;

Rectangle构造函数中,添加

this.topCorner = topCorner;

但是,说实话,centertopCorner的目的是什么? Shape#coordinates将是您正在寻找的坐标。当你的超类可以访问它时,无需在子类中创建另一个Point对象。