简体   繁体   中英

Nested Classes, Inner Class

I created an object d , right after the constructor, then another object, f , in the main method. I need to understand why is Output giving an exception ( Exception in thread "main" java.lang.StackOverflowError ). However, if I don't create the object d after the constructor, the program runs with success.

public class OuterTwo {
   public OuterTwo() {
       System.out.println("OUTER!");
   }

   OuterTwo d = new OuterTwo();

   public static void main(String[] args) {
       OuterTwo f = new OuterTwo();           
   }
}

Because your class is defined as having this field,

OuterTwo d = new OuterTwo();

Which is equivalent to

OuterTwo d;
public OuterTwo() {
  d = new OuterTwo(); // <-- this is infinite recursion.
  System.out.println("OUTER!");
}

Your code is equivalent to

public class OuterTwo {
        public OuterTwo() {
            d =new OuterTwo();
            System.out.println("OUTER!");   
        }
      OuterTwo d;
      public static void main(String[] args) {
            OuterTwo f = new OuterTwo();           
      }
    }

which is leading an infinite recursion.

You have done a small mistake here. Use something like this.

public class OuterTwo {

     OuterTwo d;

     public OuterTwo() {
          d =new OuterTwo();
          System.out.println("OUTER!");
     }

     public static void main(String[] args) {
          OuterTwo f = new OuterTwo();           
     }
}

For better understanding of Inner and Nested classes follow these links.

Inner class and Nested class

You experience stack overflow. and that is understandable. Your OuterTwo class instantiate a member of type OuterTwo. you have an infinite constructor calls to create OuterTwo objects that holds a reference to an OuterTwo object, on and on..all over again.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM