my dog learned polymorphism*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Constructors can Return Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Constructors can Return" Watch "Constructors can Return" New topic
Author

Constructors can Return

Sandeep Chhabra
Ranch Hand

Joined: Aug 28, 2005
Posts: 340
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


Regards<br />Sandy<br />[SCJP 5.0 - 75%]<br />[SCWCD 1.4 - 85%]<br />------------------<br />Tiger, Tiger burning bright,<br />Like a geek who works all night,<br />What new-fangled bit or byte,<br />Could ease the hacker's weary plight?
Joseph Clark
Ranch Hand

Joined: Sep 10, 2005
Posts: 48
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

Joined: Apr 13, 2003
Posts: 1088
Hi Sandeep

Maybe it is useful in loops or some if test.

Example :
Barry Gaunt
Ranch Hand

Joined: Aug 03, 2002
Posts: 7729
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 ]

Ask a Meaningful Question and HowToAskQuestionsOnJavaRanch
Getting someone to think and try something out is much more useful than just telling them the answer.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Constructors can Return
 
Similar Threads
[only Constructor]...
Constructurs advanteges..
Constructor problem
Extending Arrays class
constructor with return value