java - 在构造立方体和矩形对象期间堆栈溢出
问题描述
我是java的新手。今天学习了对象内的对象,并用下面的类进行了尝试,但是在构造过程中遇到了堆栈溢出错误。
我有 3 个类:Shape
扩展Rectangle
类Cube
和一个演示类。
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 - “Native Crash At”发生在我的 App 用户身上
- mysql - 从多列值计算百分比
- javascript - 选中复选框时如何使用jquery在传单上显示饼图?
- javascript - 如何通过使用变量映射将缩小的 JavaScript 转换为未缩小的 JavaScript
- javascript - Group Array of objects table 1 嵌套表 2 中的键。 MySql - NodeJS (GET API)
- javascript - 井字游戏中计算机的随机位置选择无法正常工作
- java - 在杰克逊反序列化期间验证 JSON 有效负载时如何抛出异常?
- vue.js - 如何在 Vue 或其他框架中使用 rxjs 自定义 longpress 指令?
- java - 为什么java mail api会抛出异常?
- class - Kotlin:自定义类实例上未解决的引用