Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

constructors in java  RSS feed

 
jai jai
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi ,
i have a doubt on java constructor.
the question is i have a class named example,
for this class which one will be the constructor
example() or void example().pls help me to clear this doubt.if both are constructors means is there any difference between them?


thx
jai
 
ramprasad madathil
Ranch Hand
Posts: 489
Eclipse IDE Java Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
one's a contructor
the other (with a return type) is a method.

Next time, please take care to post your question in the correct forum(This should belong to Java Beginners forum rather than the Servlet forum). You would get faster responses that way. Also, it would save the moderators the trouble of shifting it to the appropriate forum.

Thanks,
Ram.
 
kri shan
Ranch Hand
Posts: 1489
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
HI Jai, Constructors should not have return type even void.
 
David O'Meara
Rancher
Posts: 13459
Android Eclipse IDE Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Moving to Java in General (beginner)
 
Rama SManian
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
constructor cannot return anything. so you can safely define
example(){}

however you can overload a constructor
example(String name){}
 
Maureen Charlton
Ranch Hand
Posts: 218
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Another thing to note is the name of the constructor is the same as the class name i.e. class Example (with a capital letter for a class name) has a constructor
Example( )
{
}//end constructor Example

which never has a return type i.e. void, String, int

If it has a return type i.e.

public void example ( )
{
}//end method example which returns nothing

or

public String example ( )
{
String name = "Fred";
return String
}//end method example which returns a String


.....then it is a method.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!