Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

constructor returning

 
Gil Li
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
  • 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[])
{

}

}
 
somkiat puisungnoen
Ranch Hand
Posts: 1312
  • Mark post as helpful
  • send pies
  • 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.
 
Pradeep bhatt
Ranch Hand
Posts: 8927
Firefox Browser Java Spring
  • Mark post as helpful
  • send pies
  • 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.
 
fred rosenberger
lowercase baba
Bartender
Posts: 12122
30
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • 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.
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • 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...
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic