wood burning stoves 2.0
The moose likes Beginning Java and the fly likes constructor  returning Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "constructor  returning" Watch "constructor  returning" New topic

constructor returning

Gil Li

Joined: May 27, 2004
Posts: 15
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[])



Regards,<br /> <br />GILLI
somkiat puisungnoen
Ranch Hand

Joined: Jul 04, 2003
Posts: 1312
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.

Java Developer, Thailand
Pradeep bhatt
Ranch Hand

Joined: Feb 27, 2002
Posts: 8927

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

Joined: Oct 02, 2003
Posts: 11955

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.

There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
Ilja Preuss

Joined: Jul 11, 2001
Posts: 14112
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...

The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus
I agree. Here's the link: http://aspose.com/file-tools
subject: constructor returning
It's not a secret anymore!