gpt4 book ai didi

java - 正方形构建程序返回错误的措施

转载 作者:行者123 更新时间:2023-11-29 05:12:15 24 4
gpt4 key购买 nike

所以我必须编写一个程序来继承 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 类一个 Rectangle 字段,而是让这个类使用它自己内在的 Rectangleness。请记住,它本身一个 Rectangle,因为它继承自此类。

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

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(???);

// .... ???
}

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

关于java - 正方形构建程序返回错误的措施,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28006639/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com