0
What is the use of constructors when creating a class?
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);
+ 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..
+ 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.
+ 1
ByRuss X i do understand
I did a lil java the syntax is similar with c#
Thanks
0
So create constructors for your class its a must?
0
Ngandu Kennedy Bonianga no it's optional.
0
thanks guys đđŸ
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 ;)