Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why would you have two constructors with the same signature?

Tags:

java

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.

like image 284
unj2 Avatar asked May 16 '10 00:05

unj2


People also ask

Can two constructors have the same signature?

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.

Can we have more than one constructor with same signature in a class?

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.

What is the purpose of having multiple constructors?

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.

Can two constructors have the same name?

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.


1 Answers

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.

like image 183
CPerkins Avatar answered Sep 30 '22 03:09

CPerkins