Insanovation
Insanovation

Reputation: 345

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();           
   }
}

Upvotes: 2

Views: 103

Answers (4)

Deepu--Java
Deepu--Java

Reputation: 3820

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.

Upvotes: 2

Qadir Hussain
Qadir Hussain

Reputation: 1263

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

Upvotes: 1

buddy123
buddy123

Reputation: 6297

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.

Upvotes: 0

Elliott Frisch
Elliott Frisch

Reputation: 201429

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!");
}

Upvotes: 5

Related Questions