Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
167 views
in Technique[技术] by (71.8m points)

Java: object creation causes runtime error

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

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
}

and

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

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

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

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?

Thank you

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I think you have a recursive Object initialization.

Class1 obj = new Class1(); is an instance statement, so it's called at every instance, recursively, initiated from your main method.

This will cause a StackOverflowError.

The StackOverflowError is the JVM's way of telling you you are overflowing the stack memory, and the easiest way to trigger one is through infinite method or constructor recursion, such as in your case.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...