创建本地和实例对象时出现java StackOverflowError

编程入门 行业动态 更新时间:2024-10-28 12:22:53
本文介绍了创建本地和实例对象时出现java StackOverflowError的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

您好,有人可以向我解释一下为什么此代码段给了我StackOverflowError 如果您能解释instanceObj初始化并调用ObjectTest构造函数和java.lang.Object构造函数时发生的情况,我将不胜感激.在我看来,ObjectTest构造函数会不断循环.但是我不知道确切的原因吗​​?所以有什么建议...

Hi can anybody please explain me why is this code snippet giving me StackOverflowError I really appreciate if you can explain what is happening when instanceObj initializing and calling ObjectTest constructor and java.lang.Object constructor. It seems to me ObjectTest constructor loop over and over.But I don't know exact reason? So any suggestion...

public class ObjectTest { public ObjectTest() { } ObjectTest instanceObj = new ObjectTest(); public static void main(String[] args) { ObjectTest localObj = new ObjectTest(); } }

推荐答案

让我们看看将执行什么:

Let's see what will be executed :

  • main()创建ObjectTest
  • 的新实例
  • ObjectTest类具有一个字段instanceObj,该字段将包含一个ObjectTest
  • instanceObj用新的ObjectTest
  • 初始化
  • 转到第2步
  • main() create a new instance of ObjectTest
  • the ObjectTest class has a field instanceObj which will contain an ObjectTest
  • the instanceObj in initialized with a new ObjectTest
  • go to step 2
  • 我认为您想要更多类似这样的东西:

    I think you wanted something more like this :

    public class ObjectTest { private static ObjectTest instanceObj; private ObjectTest() { } public static ObjectTest getInstance() { if (instanceObj != null) { instanceObj = new ObjectTest(); } return instanceObj; } public static void main(String[] args) { ObjectTest localObj = ObjectTest.getInstance(); } }

    或者这个:

    public class ObjectTest { private static final ObjectTest instanceObj = new ObjectTest(); private ObjectTest() { } public static ObjectTest getInstance() { return instanceObj; } public static void main(String[] args) { ObjectTest localObj = ObjectTest.getInstance(); } }

    这是Singleton模式.

    This is the Singleton pattern.

    关于同一主题:

    • 为什么会出现StackOverflowError
    • java类中的循环依赖
    • Why I'm getting StackOverflowError
    • Circular dependency in java classes

    更多推荐

    创建本地和实例对象时出现java StackOverflowError

    本文发布于:2023-11-14 21:42:32,感谢您对本站的认可!
    本文链接:https://www.elefans.com/category/jswz/34/1588571.html
    版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
    本文标签:实例   对象   StackOverflowError   java

    发布评论

    评论列表 (有 0 条评论)
    草根站长

    >www.elefans.com

    编程频道|电子爱好者 - 技术资讯及电子产品介绍!