• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

signature of constructor

 
Ranch Hand
Posts: 386
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Rancher
Posts: 618
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Java Cowboy
Posts: 16084
88
Android Scala IntelliJ IDE Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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:

 
Marshal
Posts: 79416
377
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic