Hello,
What is the difference between constructor and method ?
Loading
Know the answer? Post it. Somebody with the same question will find it here.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
Javeed M ShaikhRank #839 · 2.7K reputationPosted Oct 12, 2011, 8:59 AM EDT
Following are the differences:
1. A Method needs to be explicitly called while a constructor is invoked automatically.
2. Method can be of any name but a constructor has to be of the same name that of class.
3. The constructor need not have a return type in the signature, so no return value or return statement.
4. If there is no constructor the compiler automatically creates one while running the application.
Please do not forget to mark "Accepted Answer".
VulpesRank #55 · 29.2K reputationPosted Oct 12, 2011, 9:07 AM EDT
Satyapriya NayakRank #47 · 31.5K reputationPosted Oct 12, 2011, 9:12 AM EDT
Please refer the below link
http://www.interviewcorner.com/Answer/Answers.aspx?QuestionId=999&MajorCategoryId=8&MinorCategoryId=41
Thanks
AartiRank #2,383 · 594 reputationPosted Nov 15, 2011, 3:02 AM EST
Constructor needs to have the same name as that of the class whereas functions need not be the same.
this), or a call on the superclass constructor (usingsuper). If the first line is neither of these, the compiler automatically inserts a call to the parameterless super class constructor.Thanks.
Datta KharadRank #2,135 · 668 reputationPosted Nov 15, 2011, 4:04 AM EST
Difference between Constructor and Method as follows:
A constructor only works when you create a new instance of a class. This is the very first method to run on an instance, it has to run, and it runs exactly once.
A method on an instance can be called anywhere between zero times to infinite times on an instance once it is created.
A constructor is run implicitly. When a new instance of a class is created, it runs automatically. A method is run explicitly. It has to be called either from some outside source or from a method -or a constructor- in the class.
A constructor is intended to be used for wiring. In the constructor, you want to avoid doing actual work. You basically prepare the class to be used. A method is intended to do actual work.
public class MyType
{
private SomeType _myNeeds;
// constructor
MyClass(SomeType iWillNeedThis)
{
_myNeeds = iWillNeedThis;
}
// method
public void MyMethod()
{
DoSomethingAbout(_myNeeds);
}
}
Please mark as Accepted answer if your query resolved.
AartiRank #2,383 · 594 reputationPosted Nov 15, 2011, 7:20 PM EST