Is constructors used for only Initialization? consider this code | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Is constructors used for only Initialization? consider this code

Instead of using constructors i can write my code as public class Vehicle { private String color="Red"; } what is the difference between this code and the one using constructors?

27th Jan 2017, 9:56 AM
Saisesh nag
Saisesh nag - avatar
2 Answers
+ 2
The difference is that when you create objects of that class this value will be set to red for all of them. if you use constructors you can pass a variable as parameter and change it upon object creation. public class Vehicle { private string color; public Vehicle (string col) { color = col; } } Vehicle car = new Vehicle ("red"); Vehicle bus = new Vehicle ("blue"); And so on... You get the point
27th Jan 2017, 9:59 AM
Nikolai Russev
Nikolai Russev - avatar
+ 1
yeah, now i understood it is useful to set different variables.Thank you
27th Jan 2017, 10:05 AM
Saisesh nag
Saisesh nag - avatar