Why are constructor calls in Java allowed only once per instance? If would be useful to set multiple instance variables in one call rather than calling several setters.
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
If you want to set several variables at once just define a function:
By definition an object is only constructed once, hence the constructor is only called once.
One thing worth noting: it’s more common to favour immutability, so:
because a lot of concurrency issues simply go away when you do this. Not just concurrency issues too.
String,BigDecimal,BigIntegerand some other standard classes are immutable (immutable means once instantiated its state can never change).Dateisn’t. You see in the above code I have to constantly defensively copy the date of birth? That’s becauseDateis not immutable. If you didn’t a caller could do this:The date of birth will have changed. That problem is caused solely by
Datebeing mutable. That’s another reason to favour immutability.