Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Help with constructor

 
Arun Maalik
Ranch Hand
Posts: 216
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.)
 
Shaan Shar
Ranch Hand
Posts: 1249
Java Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
sushma sree
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 288
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic