创建对象而不会导致堆栈溢出错误? [英] Create objects without causing a stack overflow error?

查看:47
本文介绍了创建对象而不会导致堆栈溢出错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,我有一个主类,它在运行时调用 private Secondary Secondary = new Secondary(); .在Secondary类中,在顶部,我有说 private Main main = new Main(); .

So, I have my main class that calls private Secondary secondary = new Secondary(); when it runs. In the Secondary class, at the top I have code that says private Main main = new Main();.

如何在不引起堆栈溢出错误的情况下使用次要类中的所有方法和变量,反之亦然?

How will I be able to use all of the methods and variables from the Secondary class and vice versa without causing a stack overflow error?

注意:它们不在构造函数中

Note: they are not in the constructor

推荐答案

您的Main类正在创建一个Secondary实例,这正在创建Main实例...,这会导致堆栈溢出错误.

Your Main class is creating a Secondary instance, which is creating a Main instance..., and this is causing the stack overflow error.

我认为您只希望对象相互引用,所以不要在构造函数中创建另一个类的新实例.将引用声明为实例变量,并使用setter方法将现有引用存储为其他类型的对象.

I think you just want the objects to refer to each other, so don't create the other class's new instance in the constructor. Declare references as instance variables, and use setter methods to store existing references to objects of the other type.

这篇关于创建对象而不会导致堆栈溢出错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆