Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/333.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 正方形构造程序返回错误的度量值_Java - Fatal编程技术网

Java 正方形构造程序返回错误的度量值

Java 正方形构造程序返回错误的度量值,java,Java,因此,我必须编写一个程序,继承要求正方形中心和边长的Rectangle类 import java.awt.Rectangle; public class Square extends Rectangle { /** Constructs a square given the center and side length * @param centerX * @param centerY * @param side */ public Sq

因此,我必须编写一个程序,继承要求正方形中心和边长的
Rectangle

import java.awt.Rectangle;

public class Square extends Rectangle {
    /** Constructs a square given the center and side length
     * @param centerX
     * @param centerY
     * @param side
     */
    public Square(int centerX, int centerY, int side) {
        square = new Rectangle();
        square.setLocation(centerX - side / 2, centerY - side / 2);
        square.setSize(side, side);
    }

    /** Returns the area of the square
     * @return area
     */
    public double getArea() {
        return (square.getWidth() * square.getWidth());
    }

    private Rectangle square;
}
这是测试程序:

public class SquareTester {
    public static void main(String[] args) {
        Square square = new Square(50, 50, 100);
        System.out.println(square.toString());
        System.out.println("Area: " + square.getArea());
    }
}
虽然它应该返回:

Square[x=0,y=0,width=100,height=100]
Area: 10000.0
程序将返回以下内容:

Square[x=0,y=0,width=0,height=0]
Area: 10000.0

我的代码怎么了?

没有给Square类一个矩形字段,而是让这个类使用它自己固有的矩形。请记住,它本身是一个矩形,因为它继承自该类

换句话说,去掉这一行/字段:

private Rectangle square;
在构造函数中,一定要调用
super
构造函数来帮助您实现这一点

public class Square extends Rectangle
{
    /** Constructs a square given the center and side length
    @param centerX
    @param centerY
    @param side
    */
    public Square(int centerX, int centerY, int side)
    {
        super(???);

        // .... ???
    }

请注意,我们没有您的矩形代码的副本,因此我无法确切地告诉您超级调用应该是什么样子,但我相信您可以解决这个问题。

非常感谢您,我忘了我应该为子类使用超级构造函数。现在它工作得很好@基于您并没有将此和答案标记为解决方案的事实,我认为您可能不熟悉接受答案机制。在这种情况下,考虑多读一些。