问题是要创建两个子类的对象并将它们存储在数组中。 因此,我创建了一个抽象的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();
}
}
}
答案 0 :(得分:1)
您已经将两个元素都存储在一个数组中,我认为您的问题与这部分更相关:
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
类的类似调整)。
目前,您正在打印Object
的{{1}}版本,因为您没有提供新的版本。通过覆盖该方法,您应该在将循环转换为以下内容后获得所需的输出:
toString
for (int i = 0; i < usegeometric.length; i++) {
System.out.println(usegeometric[i]);
}
的实际作用不是打印对象本身,而是由println
方法提供的对象的字符串表示形式。
答案 1 :(得分:0)
公共类UseGeometric {
public static void main(String[] args) {
// TODO Auto-generated method stub
GeometricFigure[] usegeometric = { new Square(12, 15), new Triangle(21, 18) };
for (int i = 0; i < usegeometric.length; i++) {
System.out.println("Area is: " + usegeometric[i].area());
}
} }