| Author |
retyrn type compulsory
|
Arnb Sen
Ranch Hand
Joined: Feb 23, 2004
Posts: 145
|
|
Hi All, Is it compulsory to mention the return type as "void" for methods which do not return anything ?
|
Regards,<br />Arnab
|
 |
Marilyn de Queiroz
Sheriff
Joined: Jul 22, 2000
Posts: 9033
|
|
Yes. What happens when you declare a method without a return type of any kind? [ September 03, 2005: Message edited by: Marilyn de Queiroz ]
|
JavaBeginnersFaq
"Yesterday is history, tomorrow is a mystery, and today is a gift; that's why they call it the present." Eleanor Roosevelt
|
 |
Arnb Sen
Ranch Hand
Joined: Feb 23, 2004
Posts: 145
|
|
Hi Marilyn, Shows compile time error.
|
 |
Arnb Sen
Ranch Hand
Joined: Feb 23, 2004
Posts: 145
|
|
So it means that Costructor is the only method which may not have a return type. However, Constructor may have a return type. Are the above statements correct ?
|
 |
Stuart Gray
Ranch Hand
Joined: Apr 21, 2005
Posts: 410
|
|
Try it and see. What does this class do? Does it compile?
|
 |
Marilyn de Queiroz
Sheriff
Joined: Jul 22, 2000
Posts: 9033
|
|
|
If a constructor has a return type, it is no longer a constructor.
|
 |
Arnb Sen
Ranch Hand
Joined: Feb 23, 2004
Posts: 145
|
|
Hi Stuart, The above vode results in compilation error. However, if I change to the code compiles without any error. So can I say that Constructors can either have no return type or can have only "void" return type ? Also, since Marilyn mentioned
If a constructor has a return type, it is no longer a constructor.
does it mean that it is possible to have methods with same name as the class name which are not constructors ?
|
 |
Jim Yingst
Wanderer
Sheriff
Joined: Jan 30, 2000
Posts: 18670
|
|
[Arnab]: So can I say that Constructors can either have no return type or can have only "void" return type ? No, because as Marilyn said, if there's a return type (including void), it's not a constructor anymore. Unfortunately this is a case where "try it and see" doesn't really give you a clear answer. The code compiles, but it doesn't do what you think it does. [Arnab]: does it mean that it is possible to have methods with same name as the class name which are not constructors ? Yes, unforturnately. This is an extremely bad idea, something that you should never do when writing a program (because it's needlessly confusing to everyone), and I wish that Sun had forbidden this in the first place. Unfortunately, they didn't. So you must remember it yourself: never put a return type, including void, on a constructor - or it stops being a constructor.
|
"I'm not back." - Bill Harding, Twister
|
 |
Stuart Gray
Ranch Hand
Joined: Apr 21, 2005
Posts: 410
|
|
|
Yeah, my bad. The example I gave doesn't compile - but for a different reason (no return statement).
|
 |
 |
|
|
subject: retyrn type compulsory
|
|
|