Java:对象创建导致运行时错误 [英] Java: object creation causes runtime error

查看:73
本文介绍了Java:对象创建导致运行时错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Java 新手,我正在尝试一些示例来了解它的工作原理.

I am new to Java and I am trying some examples to understand how it works.

我在理解以下代码失败的原因时遇到问题.我知道导致错误的行,但我不知道为什么.我创建了两个类,Class1Main,它们的代码写在两个单独的 .java 文件中:

I am having problems understanding why the following code fails. I know the line that causes the error but I can't tell why. I made two classes, Class1 and Main, whose code is written in two separate .java files:

public class Class1
{
    int var;
    public void method1 ()
    {
        System.out.println(var);
    }
    Class1 obj1 = new Class1(); // this is the line that causes the error
}

public class Main
{
    public static void main (String[] args)
    {
        Class1 obj = new Class1();
        obj.method1();
    }
}

它编译得很好,但是当我运行 java Main 时,它只会打印数百次错误

It compiles fine, but when I run java Main it just prints hundreds of times the error

at Class1.<init>(Class1.java:8)

我尝试运行 java Main |更多(我正在使用 Unix Bash)但是管道以某种方式被忽略,我看不到错误消息的第一行.java Main > 也没有.log.txt 输出重定向到文本文件的工作.如果我删除该行,即如果我不在 Class1 类主体中创建 Class1 对象 obj1,则一切正常.谁能向我解释那条线有什么问题?

I tried running java Main | more (I am using Unix Bash) but the pipe gets somehow ignored and I can't see the first line of the error message. Nor does java Main > log.txt output redirection to a text file work. If I remove that line, i.e. if I don't create the Class1 object obj1 in the Class1 class body, everything works fine. Can anyone explain to me what's wrong with that line?

谢谢

推荐答案

问题是您正在无限循环中创建 Class1 对象.

The problem is you are creating Class1 object in an infinite loop.

当您在 main 方法中创建 Class1 对象时,它会初始化您在 Class1 主体中定义的所有变量.但是由于您还在 Class1 主体内部创建了一个新的 Class1 对象,因此它会不断创建 Class1 对象,并且在某些时候会导致堆栈溢出错误.

When you create an Class1 object in main method, it initializes all variables you have defined in Class1 body. But since you also create a new Class1 object inside of Class1 body, it keeps creating Class1 object and at some point, it will cause stack overflow error.

这篇关于Java:对象创建导致运行时错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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