Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to differentiate two constructors with the same parameters?

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?

like image 631
cibercitizen1 Avatar asked Mar 15 '10 09:03

cibercitizen1


People also ask

Can we have two constructors with same parameters?

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.

Can we create multiple constructor in same class with same argument and data types?

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.

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

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.

Can we include two constructors with unique arguments in Java 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.


1 Answers

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); 
like image 199
Mykola Golubyev Avatar answered Sep 20 '22 00:09

Mykola Golubyev