Hi, I have tried to understand what is a constructor, can some one give me an easy explanation, my understanding is that it is a type of method, inside a particular class, but can someone help me understand it better. Thank you.
When you instantiate a new object, a specific constructor is called once and only once, for each instantiation of said class.
You should only use a constructor to initialise (typically) private member variables that are relied upon by methods contained within that object.
Think of it like buying furniture from IKEA. If they sold you all the pieces for a desk, but they aren't actually assembled into a desk yet, that would be like an object without a constructor. An object with a constructor would be if you buy a fully assembled desk and there's no assembly required on your part. ;-)
Now that's the default constructor (i.e. without passing any arguments). You can also have constructors where you pass some parameters to it so you can customize how you want that object to look.
A constructor isn't a method.
It doesn't have a return statement, and you may not call a constructor for an existing Object.
You invoke the constructor by calling 'new' which is another difference to methods.
The constructor creates a new Object, and returns a reference to that object.
Or put another way, a constructor is an operator (in the mathematical sense) whose domain is a class (which is abstract in the mathematical sense although in Java, "abstract" means something more particular) and whose range is objects.
This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
By continuing to use this site, you are consenting to our use of cookies.