Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

A constructor's return type cannot be void, but..  RSS feed

 
Frankie Chee
Ranch Hand
Posts: 43
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I was tried a statement from Ashraf Fouad Ayoub's notes:
'A constructor does not declare any return type, <b>not even void</b>. A constructor cannot be final, static or abstract'


The above compiles when a constructor cannot have void return type.
So what exactly is happening here?
 
Craig Wood
Ranch Hand
Posts: 1535
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
void Book() is a method signature — has a return type.
public Book() is a constructor — no return type and matches the class name.
 
Davy Kelly
Ranch Hand
Posts: 384
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Frankie,
the main point here about constructors is the return type. if a constructor does have a return type: void, int, double, String, etc then it automatically is a method.
in other words, if a method (with the same name as the class, in this case Book)does not have a return type, then it is a constructor.
if you ever come across questions about what return type should the constructor have? click the none answer.

hope this helps
Davy
[ March 02, 2004: Message edited by: Davy Kelly ]
 
Dirk Schreckmann
Sheriff
Posts: 7023
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
To be excessively clear, in Java, it might be unfortunate and a design flaw of the language, but a method is allowed to have the same name as the class.
This and other potential pitfalls listed in Roedy Green's Java Glossary : Gotchas are good to be familiar with.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!