• 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

Constructors can Return

 
Ranch Hand
Posts: 340
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,
An abstract from Khalid A. Mughal book for SCJP 1.4 says

Constructors cannot return a value and, hence, cannot specify a return type, not even void, in the constructor header, but they can contain the simple form of the return statement in the constructor body.


hence:


would compile and run and print Constructor.
But i dont understand why would we ever need to use empty return statement in a constructor when actually it cannot return anything?

Thanx
Sandy
 
Ranch Hand
Posts: 48
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The only reason I can think of would be to return out of some kind of conditional construct.


if(some condition){
//do something
return;
}
else if (something other condition){
//do something else
return;
}
else{
//whatever
}
 
Ranch Hand
Posts: 1090
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Sandeep

Maybe it is useful in loops or some if test.

Example :
 
Ranch Hand
Posts: 7729
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
As Michael wrote, you may want to quickly get out of the constructor for some reason. You would still have an instance of the object being constructed, but it would possibly be only partially initialised.

This early return technique is also useful in any method returning void.
[ September 11, 2005: Message edited by: Barry Gaunt ]
 
For my next feat, I will require a volunteer from the audience! Perhaps this tiny ad?
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic