aspose file tools
The moose likes Java in General and the fly likes class X that contains class X Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login
JavaRanch » Java Forums » Java » Java in General
Reply Bookmark "class X that contains class X" Watch "class X that contains class X" New topic
Author

class X that contains class X

Hendra Kurniawan
Ranch Hand

Joined: Jan 31, 2011
Posts: 239
I have a class like this:


At first glance, it should produce stack overflow when you allocate new X(), because everytime you call new X(), the constructor will call new X(), which in turn will call new X(), and so on. But when I tried running this, the code compiled and ran just fine. I don't get it. Could anybody explain this phenomenon? thanks
Winston Gutkowski
Bartender

Joined: Mar 17, 2011
Posts: 4761
    
    7

Hendra Kurniawan wrote:At first glance, it should produce stack overflow when you allocate new X(), because everytime you call new X(), the constructor will call new X(), which in turn will call new X(), and so on. But when I tried running this, the code compiled and ran just fine. I don't get it. Could anybody explain this phenomenon? thanks

Ah. That would be because 'x' is not an X, but an X[], which is something quite different. Change
for(int i=0;i<10;i++) x[i]=null;
to
for(int i=0;i<10;i++) x[i]=new X();
and you'll soon find out what I mean.

Winston


Isn't it funny how there's always time and money enough to do it WRONG?
Jeff Verdegan
Bartender

Joined: Jan 03, 2004
Posts: 5895
    
    6

Hendra Kurniawan wrote:I have a class like this:


At first glance, it should produce stack overflow when you allocate new X(), because everytime you call new X(), the constructor will call new X()


Nope. new X[len] is not the same as new X(). The former creates an array full of nulls, and does not create any X objects. And because of this, the for loop in the constructor is pointless, since all the array elements are initialized to null at array creation and only change when we explicitly set them.


Hendra Kurniawan
Ranch Hand

Joined: Jan 31, 2011
Posts: 239
Ah, it's clear now. Thank you very much. Have a nice day!!
 
I agree. Here's the link: http://zeroturnaround.com/jrebel - it saves me about five hours per week
 
subject: class X that contains class X
 
Similar Threads
refresh label
Inheritance --- Assigning Sub class Object to Super Class Reference
why private member variable of inner class can't be accessed by its outer class but mehod can be?
why constructer for abstract class?
JPopupMenus