首页 > 解决方案 > 在构造立方体和矩形对象期间堆栈溢出

问题描述

我是java的新手。今天学习了对象内的对象,并用下面的类进行了尝试,但是在构造过程中遇到了堆栈溢出错误。

我有 3 个类:Shape扩展RectangleCube和一个演示类。

public class Shape{
    public Shape() {
        System.out.println("Constructor of Shape.");
    }   

    public Rectangle rec = new Rectangle(10, 14);
}

public class Rectangle extends Shape{
    public Rectangle(int width, int height) {
        super();
        this.width = width;
        this.height = height;
    }

    int width, height;
}

public class DemoShape{
    public static void main(String[] args) {
        Shape c = new Shape();
        System.out.println(c.rec.getArea());
}

错误返回:

Exception in thread "main" java.lang.StackOverflowError
    at ObjectWithinAnObject.p2.Rectangle.<init>(Rectangle.java:6)
    at ObjectWithinAnObject.p2.Shape.<init>(Shape.java:9)
    at ObjectWithinAnObject.p2.Rectangle.<init>(Rectangle.java:6)
    at ObjectWithinAnObject.p2.Shape.<init>(Shape.java:9)
    at ObjectWithinAnObject.p2.Rectangle.<init>(Rectangle.java:6)
    at ObjectWithinAnObject.p2.Shape.<init>(Shape.java:9)

我将 Cube 更改为 Shape 以消除混乱。

标签: java

解决方案


推荐阅读