• 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

constructor returning

 
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hello people
I heard that constructor doesnot return anything.But I tried the following code. I cant understand the real thing about constructor.Help me.


/*
This code compiles without any problems
*/

class sample {

public int sample()
{

return 5;
}


public static void main(String a[])
{

}

}
 
Ranch Hand
Posts: 1312
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
In java specification,

Contructor not have return type, name like class name, can define public/private/default.

In your code.




public int sample() is method for this class ,not constructor.
 
Ranch Hand
Posts: 8945
Firefox Browser Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
is a method and not a constructor.

It is valid to have a method name same as the Constructor name. This should be avoided so as not to create confusion.
 
lowercase baba
Posts: 13091
67
Chrome Java Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
While a constructor must have the same name as the class, it also CANNOT have a return type. as soon as you put that 'int' into the line ' public int sample()', you no longer had a constructor, but a method.

as others have pointed out, it's a bad choice for a method name, but it is a legal one.
 
author
Posts: 14112
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Originally posted by fred rosenberger:

as others have pointed out, it's a bad choice for a method name, but it is a legal one.



As an aside, the eclipse compiler can be configured to flag this as a warning or even error. I think that's a good idea...
 
reply
    Bookmark Topic Watch Topic
  • New Topic