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

signature of constructor  RSS feed

 
nirjari patel
Ranch Hand
Posts: 386
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Do I need to specify "void" return type for constructor ?

If I tpye public TestConstructor() {}

Will it be automatically considered void by compiler ?

If I just type TerstConstructor() {}, will that be a legal name for contructor ?

Thanks
 
Tom Reilly
Rancher
Posts: 618
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Do I need to specify "void" return type for constructor ?
Constructors never have return types. If you specify a return type then it is no longer a constructor. It is a method with the same name as the class.
If I tpye public TestConstructor() {}

Will it be automatically considered void by compiler ?
That is a valid constructor.
If I just type TerstConstructor() {}, will that be a legal name for contructor ?
Yes, if your class is called TerstConstructor. If your class is called TestConstructor then this will be a compiler error because the compiler will see it as a method without a return type.
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16028
87
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

As Tom said, constructors don't have a return value, so you don't have to specify a return type.

In fact, constructors are not methods, even though they look like methods. A constructor is a special block of code that is called by the JVM when a new instance of the class is created.

When you specify a return type, then it's not a constructor anymore, but just a regular method. That can be tricky:

 
Campbell Ritchie
Marshal
Posts: 55691
163
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can probably understand Jesper's last example better if you examine the bytecode. Use either of these instructions (which produce different displays):

javap MyClass
javap -c MyClass
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!