Why is it eligible for a Java class to declare and initialize an object of that class in a method?

Q.Z. Shen :

I have the following code example:

public class example {

  // class constructor
  public example(){}

  public void foo() {
    example o = new example();
    ...
  }
}

Why can this be compiled and run instead of leading to a StackOverflowError?

Sweeper :

You claim that this would lead to a StackOverflowError. However, a StackOverflowError will only occur if a method calls itself, either directly or indirectly, indefinitely.

In your case, foo must call itself to make a stack overflow happen. Let's see what foo does.

example o = new example();

When foo is called, it would call the constructor of example, which you have declared here:

public example(){}

The constructor does nothing before returning. Now that the constructor has returned, o is assigned the newly created instance, and foo returns since it has nothing else to do. Note that foo has not been called again.

Your misunderstanding might be that you wrongly thought that when the constructor is called, all of the methods of that class are also called. This is not true, unless you actually call the methods in the constructor:

public example(){ foo(); } // this will cause stack overflow

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=129442&siteId=1