• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

StackOverFlowError in inner class

 
raghu dubey
Ranch Hand
Posts: 72
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Whu does the line below throw an StackOverFlowError. I understand that the syntax is not correct for inner class, but could you please explain whats is happening under the hood:

======
package chap_8;

public class OutClass {

private int i = 20;
public class Inclass{

private int i=10;
}

static Inclass ind = new OutClass().new Inclass();//Compiles and runs
Inclass ind1 = new OutClass().new Inclass();//StackOverflowError

Inclass ind2 = new Inclass();//compiles and runs

public static void main(String[] args) {
OutClass.Inclass in = new OutClass().new Inclass();
System.out.println(in.i);
}

public void test(){

Inclass in = new Inclass();
}
}
================
 
Kelvin Chenhao Lim
Ranch Hand
Posts: 513
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The problem isn't really with your inner class.

ind1 is an instance variable, so it gets initialized whenever you create an instance of OutClass. However, to initialize ind1, you create another instance of OutClass, which in turn contains another ind1 instance variable, which will be initialized by creating another instance of OutClass, which in turn contains another ind1 instance variable, ....

And so the constructor calls pile on, until the JVM runs out of stack memory. This causes your StackOverflowError.

Put another way, here's a depiction of what happens when your program executes:


[ November 03, 2007: Message edited by: Kelvin Lim ]
 
raghu dubey
Ranch Hand
Posts: 72
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Kelvin

 
Fu Dong Jia
Ranch Hand
Posts: 131
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Kelvin Lim!
 
adam Lui
Ranch Hand
Posts: 186
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Kelvin you rock my world!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic