Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...