+ 2
can we have two constructors
suppose we have two attributes i. e.. name, city. can we have different constructors for them
6 ответов
+ 10
One constructor is enough for any number of attributes.
+ 6
Constructors are meant for initialize data members on object creation. So, you can't have separate constructor for each attribute, rather than you can define setters to handle attributes individually.
+ 4
You could but it would be an absolute mess. In order to have multiple constructors they need different parameters. It would look something like this:
class cons{
cons(){
// change city
}
cons(String a){
// change name
}
}
So if you inialized the object with a string it would change the name. You could just use a string for one constructor that contains both the name and city then seperate it into 2 parts to initalize them both. But should really just go with what @Devender said
+ 2
one constructor is sufficient for it use parameterized constructor
+ 1
ya we can have two constructor but they should be different types like one default then second parameterized and so on....
+ 1
Like Pranjal said, you can have more, basically as many as you like, as long as they don't interfere with each other content-wise. When the default constructor has set attribute standards for a certain type of object that, in a specific occasion, needs to be modified: e.g. when you have a number of cars, all defined in your class as having four wheels, four windows and all need to be red... and then all of a sudden you want a car that is blue, that difference in color can be defined by a different constructor. For the method in which that car is defined, you would type this. in front, to specify that the additional constructor will apply only for this specific object in this method (please correct me if I got the concepts wrong, I'm still a noob myself).