What is the use of Constructor | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 9

What is the use of Constructor

14th May 2019, 9:20 AM
Ytbarek Gebre
Ytbarek Gebre - avatar
7 Answers
+ 26
Ytbarek Gebre ➝ Include relevant TAGS!! A 'constructor' initializes an object when it is created. It has the same name as its class and is syntactically similar to a method. However, constructors have no explicit return type. The general form of a constructor is: access class-name(param-list) { // constructor code } Typically, you will use a constructor to give initial values to the instance variables defined by the class or to perform any other startup procedures required to create a fully formed object. Also, usually, access is 'public' because constructors are normally called from outside their class. The param-list can be empty, or it can specify one or more parameters. All classes have constructors, whether you define one or not, because C# automatically provides a default constructor that causes all member variables to be initialized to their default values.
14th May 2019, 11:30 AM
Danijel Ivanović
Danijel Ivanović - avatar
+ 17
creating objects of the defined class initiating data members and calling constructors of the parents if the class extends any other classes
15th May 2019, 8:38 AM
Nour Abu Assaf
Nour Abu Assaf - avatar
+ 6
So when you create a class usually you will have⬇ public class Car{ //empty fields⬇ String model; int year;} The best way to initalize these fields is with the constructor. public class Car{ String model; int year; //constructor method⬇ Car(String model, int year){ this.model= model; this.year=year;} } Now when you create an instance of class a call to the constructor is made which initalize the fields for your new instance. Car mini = new Car("mini",1997); System.out.print(mini.year);
14th May 2019, 10:08 AM
D_Stark
D_Stark - avatar
+ 2
Initalize an instance of an class (object) with an valid state.
14th May 2019, 9:30 AM
Daniel Adam
Daniel Adam - avatar
+ 2
You can overload the constructor to use different number or type of parameters to instantiate object of the class. This leads to run-time polymorphism... 🤔
14th May 2019, 2:15 PM
Sanjay Kamath
Sanjay Kamath - avatar
+ 2
You can use constructors to create objects with special methods. You can define how the created object behaves for any operators. You can make a program to print "Hello world!" When an object is divided by 5. You can make a program to print "SoloLearn" when an object is compared.
14th May 2019, 8:41 PM
Seb TheS
Seb TheS - avatar
0
The visibility is NOT usually public. In OOP you often use other qualifiers to hide the constructors that have technical relevance only.
14th May 2019, 11:33 AM
Daniel Adam
Daniel Adam - avatar