Hello,
What is the difference between constructor and method ?
Loading
Know the answer? Post it — somebody with the same question will find it here.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
AartiPosted Nov 16, 2011, 12:20 AM
Datta KharadPosted Nov 15, 2011, 9:04 AM
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.
AartiPosted Nov 15, 2011, 8:02 AM
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.
Satyapriya NayakPosted Oct 12, 2011, 1:12 PM
Please refer the below link
http://www.interviewcorner.com/Answer/Answers.aspx?QuestionId=999&MajorCategoryId=8&MinorCategoryId=41
Thanks
VulpesPosted Oct 12, 2011, 1:07 PM
Javeed M ShaikhPosted Oct 12, 2011, 12:59 PM
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".