Balu Sadhasivam wrote:Avoid such silly typo as it shows your interest in asking questions.
Please!! Lots of people don't spell correctly. I think that comment warrants an apology.
Constructor's important use is to initialize objects.
More precisely, to make sure that all fields in an object are set to appropriate values to establish the class invariant. If the constructor doesn't establish the class invariants, it is incorrectly written.
Probably also a good idea to initialise every field in the constructor, even those where the default value of 0 is appropriate. Also probably a good idea to initialise all reference-type fields so as to avoid null values.
To paraphrase what Campbell said, the constructor allows you -- the programmer writing the class -- a change to initialize the object, if needed. All classes must have a constructor, so if you don't have any special initialization needs, you just use the default (no args) constructor. If there's information that must be provided as the object is created, you can create a constructor with parameters used to gather those values. For example, if you had a class Canine, with a "dob" (date of birth) property, and used the default no-args constructor, what would you initialize the date to? If there's a clear default, then you could code the no-args constructor and initialize the value there. If there's not, then you'd code a constructor with a dob parameter, and the calling routine would provide that value.
A lot of people forget there is a difference between a default constructor and a no-arguments constructor. A default constructor is a kind of no-arguments constructor (properly defined as one added by the compiler) with an empty body. You can also have no-arguments constructors which have real code inside their bodies.
Example:Maybe not a very useful class, but it is only there as an example.
Story like this gets better after being told a few times. Or maybe it's just a tiny ad:
a bit of art, as a gift, the permaculture playing cards