What are the use cases of having two constructors with the same signature?
Edit: You cannot do that in Java because of which Effective Java says you need static factory. But I was wondering why would you need to do that in the first place.
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.
The reason you’d think you wanted to do this is that you’ve found yourself in a situation where variable type isn’t sufficient context.
For example, I might fool myself into thinking that I need to give my Point class two constructors: one which works by X and Y, and one by degrees and radians. Both might be represented as float.
So I’d think I needed two constructors with identical signatures (float, float).
Dr. Bloch points out that it’s better to make factory methods:
Incidentally, another alternative to factory methods is to create types which carry the context which is missing from the datatypes, like this:
Whether you think this is clearer than the factory methods is a matter of taste. For this specific case, my own feeling is that the two coordinates classes are only of use if your design makes coordinates useful on their own, separate from a point at those coordinates.