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?
2 Réponses
+ 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
+ 1
yeah, now i understood it is useful to set different variables.Thank you