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

标签 java inheritance abstract

问题是创建两个子类的对象并将它们存储在数组中。 因此,我创建了一个抽象的 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/

相关文章:

inheritance - 覆盖和更改函数 Odoo 的中间部分

java - jvm如何处理java中的抽象类

c++ - 抽象类之间的组合

java - iText 7 : How can I allow overflow in a Div?

java - 使用 Linux more 命令时 Runtime.getRuntime().exec() 挂起

c++ - 我如何访问继承代码的不同部分

C++11构造函数继承和纯虚方法

java - 如何修复: Unable to invoke no-args constructor for class X: Registering an InstanceCreator with Gson for this type may fix this problem

Java SSL 错误 : Unable to retrieve certificate chain

java - Android 应用程序中的 MVP 与事件驱动