Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Constructors can Return

 
Sandeep Chhabra
Ranch Hand
Posts: 340
  • Mark post as helpful
  • send pies
  • 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
 
Joseph Clark
Ranch Hand
Posts: 48
  • Mark post as helpful
  • send pies
  • 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
}
 
Anupam Sinha
Ranch Hand
Posts: 1090
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Sandeep

Maybe it is useful in loops or some if test.

Example :
 
Barry Gaunt
Ranch Hand
Posts: 7729
  • Mark post as helpful
  • send pies
  • 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 ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic