gpt4 book ai didi

java - Java中的子类

转载 作者:行者123 更新时间:2023-12-01 16:53:49 25 4
gpt4 key购买 nike

我的 friend 给了我这个任务,我正在努力完成最后的任务,它要求我:

"implement a class called Square that represents a square. Class Square must be derived from Rectangle. Make sure you override toString()."

我什至认为我还没有接近获得它,但任何帮助都会很棒

矩形.Java

public class Rectangle {

public double width;
public double height;

public Rectangle(double width, double height) {
this.width = width;
this.height = height;
}

public double getArea() {
return width * height;
}

public double getPerimeter() {
return 2*width+2*height;
}

@Override
public String toString() {
return "Rectangle[width "+width+",height "+height+"]Area:"+getArea()+",Perimeter:"+getPerimeter();
}

public static void main(String[] args) {

double width = (10);
double height = (10);
Rectangle rectangle = new Rectangle(width, height);
System.out.println(rectangle);

}
}

Sqaure.java

public class Sqaure extends Rectangle {

private final double width, height, area, perimeter;

public Sqaure(double width, double height) {
this.width = width;
this.height= height;
}

public static void main(String[] args) {
double width = (10);
double height = (10);
Sqaure sqaure = new Sqaure(width, height);
System.out.println(square);
}
}

最佳答案

除了构造函数和toString()之外,不需要重写更多内容。由于正方形只是一个边长相等的特殊矩形,因此您只需将它们初始化为相同的值,所有其他方法都将按预期工作:

public class Square extends Rectangle {

public Square(double width) {
super(width, width);
}

@Override
public String toString() {
return "Square[width:" + width + "]Area:" + getArea() +
",Perimeter:" + getPerimeter();
}

请注意,在现实世界中,在这种情况下您可能不会使用继承,因为这会带来一些歧义——您仍然可以使用矩形构造函数创建正方形,并且人们可能会被误导使用instanceof检查来确定是否给定的矩形是正方形。相反,人们可能会添加一个参数构造函数并检查 toString 中的宽度/高度等效性。

关于java - Java中的子类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35578728/

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