Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How many nested "new" objects can be created in java?

class car{
    Salon s ;
}
class Salon{
     Radio musicsystem ;
}
class Radio{
    Button play ;
}
class Button{
     String s ;
}

void main(){
    car mustang = new car( new Salon( new Radio(new Button ("fight club song"))))
}

I can easily imagine there is lots new(new (new(new ....) )). How deep can you go? I "intuitively" feel it can be bad for the compiler/jvm/system to have too many levels of objects...

Does java have restriction on depth?

like image 258
ERJAN Avatar asked Aug 08 '26 23:08

ERJAN


1 Answers

A satisfactory answer should be, You can go much deeper than you'll ever want to see actually happen in your code.

If you want to entertain the limits just for the fun of it, I believe that the first limit you will in fact hit is the limit on the length of the bytecode of a single method, which is set at a very low 64K.

The only way to truly worry about hitting the limit is when you have recursive constructor calls, such as you might have when constructing an immutable linked list or a similar structure.

like image 136
Marko Topolnik Avatar answered Aug 11 '26 11:08

Marko Topolnik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!