• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

recursive constructor invocation

 
Ranch Hand
Posts: 270
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The following code produces a compilation error...

while the code below passes the compilation process...

but with runtime error--stack overflow.
It sounds to me that within the same class, the compiler will check for "recursive constructor invocation"(the first piece of code) while it ignores "recursive constructor invocation" in two or more classes(the second piece of code).
Can someone explains a bit on this?
Thanks in advance
 
Ranch Hand
Posts: 3271
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Yup - you're right. The compiler wasn't built by NASA engineers trying to send someone to Mars. It isn't going to check your logic to see if you're doing something you shouldn't be doing. In some cases, like your first example, the compiler will look for some simple error and tell you about them. However, what will the compiler check and what won't it check? The line had to be drawn somewhere. In many cases, the compiler simply checks syntax and puts the burden on you, the programmer, to ensure that your logic isn't causing a stack overflow or any other problem. This leads to a nice, lightweight compiler.
Could the developers of the compiler checked for such a thing as this? Probably. It also probably would have taken a lot of work for something that any competent developer should be able to avoid, anyway.
I hope that helps,
Corey
 
Ranch Hand
Posts: 1392
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

It is a compile-time error for a constructor to directly or indirectly invoke itself through a series of one or more explicit constructor invocations involving this. JLS 8.8.5

Thus, the JLS requires the compiler to produce an error in your first example.
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic