Click here to Skip to main content
15,906,081 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
what is the need of constructors and why constructors are used

What I have tried:

what is the need of constructors and why constructors are used
Posted
Updated 30-Jul-16 2:29am

Constructors are there so that when you create an instance of a class you can ensure that it has all the required information available when you try to use it.
Assume you have a Person class - you can't construct a Person without knowing a fair amount of information about them: their name, date of birth, and address for example.
Providing a constructor allows you to be sure that when the Person is created that information is supplied so that you can do this:
C#
Person mike = new Person("Mike Smith", new DateTime(1999, 1, 17), "3, Larch Lane, LarchTon");
Console.WriteLine(mike.Age());
Because your Person constructor insisted that I provide the date of birth when I create the instance, I can call the Age method and know it won't have a problem.
The same is true for default constructors: they let you ensure that everything the class needs to do it's job is created and ready before the instance is used.
 
Share this answer
 
Need of Constructor
Think of a Box. If we talk about a box class then it will have some class variables (say length, breadth, and height). But when it comes to creating its object(i.e Box will now exist in computer’s memory), then can a box be there with no value defined for its dimensions. The answer is no.
So constructors are used to assign values to the class variables at the time of object creation, either explicitly done by the programmer or by Java itself (default constructor).

When is a Constructor called ?
Each time an object is created using new() keyword at least one constructor (it could be default constructor) is invoked to assign initial values to the data members of the same class.
 
Share this answer
 
v3

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900