What is the use of constructors when creating a class? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

What is the use of constructors when creating a class?

12th Jul 2020, 8:56 PM
Ngandu Kennedy Bonianga
Ngandu Kennedy Bonianga - avatar
8 Answers
+ 1
The name suggests. Constructors let you initialize instances with the values you pass in. So you don't have to first initialize the class and then assign to attributes. So instead of Point p = new Point(); p.x = 0; p.y = 0; You can just do Point p = new Point(x, y);
12th Jul 2020, 9:09 PM
XXX
XXX - avatar
+ 2
It is used to assign default values to member variables by default constructor. And upon object creation, its respected matching arguments constructor will automatically get executed.. That's the purpose of constructor..
12th Jul 2020, 9:05 PM
Jayakrishna 🇮🇳
+ 1
The constructor is used to pass arguments to the class. for example: you create a class called house, and in the constructor you put an argument named floor. When the user passes the color, you can make it a property.
12th Jul 2020, 10:18 PM
ByRuss X
ByRuss X - avatar
+ 1
ByRuss X i do understand I did a lil java the syntax is similar with c# Thanks
12th Jul 2020, 10:39 PM
Ngandu Kennedy Bonianga
Ngandu Kennedy Bonianga - avatar
0
So create constructors for your class its a must?
12th Jul 2020, 9:15 PM
Ngandu Kennedy Bonianga
Ngandu Kennedy Bonianga - avatar
0
Ngandu Kennedy Bonianga no it's optional.
12th Jul 2020, 9:16 PM
XXX
XXX - avatar
0
thanks guys 🙏🏾
12th Jul 2020, 9:24 PM
Ngandu Kennedy Bonianga
Ngandu Kennedy Bonianga - avatar
0
I don't know OOP in C#, but in Java you can do like this: In the other example: public class House:{ //class House public String color //property color public House(String color){ //constructor this.color=color //setting class' color to the parameter } } House house1 = new House("green") //object: House color: green House house2 = new House("purple") //object: House color: purple System.out.println(house1.color) //result: green System.out.println(house2.color) //result: purple Hope you understood it ;)
12th Jul 2020, 10:28 PM
ByRuss X
ByRuss X - avatar