aspose file tools*
The moose likes Beginning Java and the fly likes Help with constructor Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Help with constructor" Watch "Help with constructor" New topic
Author

Help with constructor

Arun Maalik
Ranch Hand

Joined: Oct 25, 2005
Posts: 216
Hey sir my java code is like this
public class First{
int First(){return 1;}
public static void main(String[] args}{
First p=new First();}
}//End of First
as we know that constructor doesn't have any return type but it is working properly why? also since constructor is returning a int value how can we get that value in main?
marc weber
Sheriff

Joined: Aug 31, 2004
Posts: 11343

The method you've defined is not a constructor. It's an instance method that happens to share the name of the class.

(If you add a println to the method body, you will see that it's not executed when an instance is created.)


"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer
sscce.org
Shaan Shar
Ranch Hand

Joined: Dec 27, 2005
Posts: 1249

Dear Anu Malik,

As you are assuming that you are calling a constructer with int return type. Thats a wrong assumption if you relly want to verify it. just compile this code and run this code.


Actually it's working as a simple Method which has same name as Class. That's why you are thinking that it is working as a Constructer. But actually it's not working as a Constructer. You can verify it.So your second question is also answered now "We cann't return anything from a Constructer."

I hope this will clearify your Queries. So now This question can be closed now.. And One more thing I want to add that it will be very usefull if you try yourself such sort of codes. This will clearify you more.So next time onwards please do ownself then post it here.


The Best way to predict your future is to create it - Every great individual common man
sushma sree
Greenhorn

Joined: Mar 27, 2006
Posts: 12
The way you differentiate constructors from methods is by looking at the return type and also the name

Ex:
Class MyClass
{
MyClass()
{
}
int first()
{
}
static void main(String[] args}{
First p=new First();}
}
sushma sree
Greenhorn

Joined: Mar 27, 2006
Posts: 12
The way you differentiate constructors from methods is by looking at the return type and also the name

Ex:
Class MyClass
{
MyClass() //Constructor, no return type and same name as the class
{
}
int first() //method since it has return type
{

}
static void main(String[] args}
{
First p=new First();
}
}
ak pillai
author
Ranch Hand

Joined: Feb 11, 2006
Posts: 288


java j2ee job interview questions with answers | Learn the core concepts and the key areas
 
 
subject: Help with constructor