aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes StackOverFlowError in inner class Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "StackOverFlowError in inner class" Watch "StackOverFlowError in inner class" New topic
Author

StackOverFlowError in inner class

raghu dubey
Ranch Hand

Joined: Jul 05, 2007
Posts: 72
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();
}
}
================


Thanks,<br />Raghu.<br /> <br />SCJP 5, SCWCD 1.4, NCFM
Kelvin Chenhao Lim
Ranch Hand

Joined: Oct 20, 2007
Posts: 513
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 ]

SCJP 5.0
raghu dubey
Ranch Hand

Joined: Jul 05, 2007
Posts: 72
Thanks Kelvin

Fu Dong Jia
Ranch Hand

Joined: May 23, 2007
Posts: 131
Thanks Kelvin Lim!


who dare win!<br />SCJP5(94%)|SCWCD5(86%)|SCBCD(100%)|SCEA in progress
adam Lui
Ranch Hand

Joined: Sep 03, 2007
Posts: 186
Kelvin you rock my world!
 
Consider Paul's rocket mass heater.
 
subject: StackOverFlowError in inner class