Suppose we want two constructors for a class representing complex numbers:
Complex (double re, double img) // construct from cartesian coordinates Complex (double A, double w) // construct from polar coordinates
but the parameters (number and type) are the same: what is the more elegant way to identify what is intended? Adding a third parameter to one of the constructors?
There can be multiple constructors in a class. However, the parameter list of the constructors should not be same. This is known as constructor overloading.
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. This concept is known as Constructor Overloading and is quite similar to function overloading.
A Class cannot have two constructors with the same signature. It is a compile-time error to declare two constructors with override-equivalent (§8.4. 2) signatures in a class. It is a compile-time error to declare two constructors whose signature has the same erasure (§4.6) in a class.
Constructor Overloading - Multiple Constructors for a Java Class. A class can have multiple constructors, as long as their signature (the parameters they take) are not the same.
It is better to add static methods with appropriate names and let them to create the objects.
static Complex createFromCartesian(double re, double img); static Complex createFromPolar(double A, double w);
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