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.
A class can have only a single constructor with a given signature. Programmers have been known to get around this restriction by providing two constructors whose parameter lists differ only in the order of their parameter types. This is a bad idea.
Constructor Overloading in C++ In C++, We can have more than one constructor in a class with same name, as long as each has a different list of arguments.
A class can have multiple constructors that assign the fields in different ways. Sometimes it's beneficial to specify every aspect of an object's data by assigning parameters to the fields, but other times it might be appropriate to define only one or a few.
Java supports method name overloading so a class can have any number of constructors all of which have the same name. Like other overloaded methods, constructors are differentiated from one another by the number and type of their arguments.
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:
public static Point newPointByDegreesAndRadians (float degrees, float radians);
public static Point newPointByXandY (float x, float y);
Incidentally, another alternative to factory methods is to create types which carry the context which is missing from the datatypes, like this:
public class CoordinatesXY {
float X;
float Y;
...
}
public class CoordinatesDegreesRadians {
float degrees;
float radians;
...
}
public Point (CoordinatesXY coordinates) { ... }
public Point (CoordinatesDegreesRadians coordinates) { ... }
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With