+ 2

can we have two constructors

suppose we have two attributes i. e.. name, city. can we have different constructors for them

26th Mar 2017, 1:25 PM
shobhit
shobhit - avatar
6 ответов
+ 10
One constructor is enough for any number of attributes.
26th Mar 2017, 1:37 PM
Krishna Teja Yeluripati
Krishna Teja Yeluripati - avatar
+ 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.
26th Mar 2017, 1:37 PM
देवेंद्र महाजन (Devender)
देवेंद्र महाजन (Devender) - avatar
+ 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
26th Mar 2017, 3:37 PM
Rrestoring faith
Rrestoring faith - avatar
+ 2
one constructor is sufficient for it use parameterized constructor
26th Mar 2017, 2:09 PM
Mayur Chaudhari
Mayur Chaudhari - avatar
+ 1
ya we can have two constructor but they should be different types like one default then second parameterized and so on....
12th Apr 2017, 9:19 AM
PRANJAL AGNIHOTRI
PRANJAL AGNIHOTRI - avatar
+ 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).
14th Jul 2017, 9:14 AM
Amina Diehl
Amina Diehl - avatar