gpt4 book ai didi

java - 如何在数组中存储子类的对象?

转载 作者:行者123 更新时间:2023-12-02 10:55:50 24 4
gpt4 key购买 nike

问题是创建两个子类的对象并将它们存储在数组中。因此,我创建了一个抽象的 super 类,并创建了一个抽象的方法区域,然后创建了两个子类,并在我声明数组的主方法上实现了该方法,并给出了值,这就是它。我是新来的,如果我问错了,我很抱歉。是的,输出应该是两个图形的面积和类型。

package Geometric;

public abstract class GeometricFigure {

int height;
int width;
String type;
int area;


public GeometricFigure(int height, int width) {
//super();
this.height = height;
this.width = width;
}



public abstract int area();
}

package Geometric;

public class Square extends GeometricFigure {

public Square(int height, int width) {
super(height,width);


}
public int area(){

return height * width;

}

}

package Geometric;

public class Triangle extends GeometricFigure {

public Triangle(int height, int width) {
super(height ,width);

}
public int area() {
return (height*width)/2;
}
}
package Geometric;

public class UseGeometric {

public static void main(String args[]) {

GeometricFigure[] usegeometric = { new Square(12, 15), new Triangle(21, 18) };

for (int i = 0; i < usegeometric.length; i++) {

System.out.println(usegeometric[i]);
usegeometric[i].area();

System.out.println();
}
}
}

最佳答案

您已经将两个元素存储在数组中,我认为您的问题与这部分更相关:

usegeometric[i].area();

System.out.println();

您获得了两个元素的面积,但没有将其分配给变量,并且没有对它执行任何操作。将这些代码行更改为:

System.out.println("Area: " + usegeometric[i].area());

编辑:

Geometric.Square@19dfb72a Geometric.Triangle@17f6480

这是您可以预期的输出类型,因为您没有覆盖类中的 toString 方法。如果不这样做,它将采用继承的 Object 版本,打印 this information

--在您的 Square 类中,添加以下内容:

public String toString() {
return "Square - area = " + area();
}

或类似的内容,具体取决于您想要打印的内容。 (并对您的 Triangle 类进行类似的调整)。此时,您正在打印 ObjecttoString 版本,因为您没有提供新版本。通过覆盖该方法,您应该在将循环转换为以下内容后获得所需的输出:

for (int i = 0; i < usegeometric.length; i++) {
System.out.println(usegeometric[i]);
}

println 实际上所做的不是打印对象本身,而是打印对象的字符串表示形式,由 toString 方法提供。

关于java - 如何在数组中存储子类的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51760727/

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