Constructor parameter with int and long or double and float throwing error

214 views Asked by At

I am trying to implement constructor overloading by using int and long together and double and float together. I am passing two int values from main method and want to check which constructor gets called A(int, long) or A(long, int). I am passing two double values from main method and want to check which construcotr gets called A(double, float) or A(float, double).

In Line5, I am passing values to the constructors in Line1 and Line2 and in Line6, I am passing values to the constructors in Line3 and Line4. While compiling and executing this code, constructor is ambiguous is showing for Line5 and constructor is undefined is showing for Line6.

CODE:

import java.util.*;

public class Test {
    
    public Test(long i, int f, double d) { //Line1
        System.out.println("L i d");
    }
    
    public Test(int i, long d, double f) { //Line2 
        System.out.println("i L f");
    }
    
    public Test(int i, float f, double d) { //Line3
        System.out.println("i f d");
    }
    
    public Test(int i, double d, float f) { //Line4
        System.out.println("i d f");
    }
    
    public static void main(String[] args) {
        Test ob = new Test(1, 2, 4.14); //showing compilation error //Line5
        Test ob1 = new Test(1, 2.33, 4.14); //showing compilation error //Line6
    }
}

OUTPUT:

Exception in thread "main" java.lang.Error: Unresolved compilation problems: 
    The constructor Test(long, int, double) is ambiguous
    The constructor Test(int, double, double) is undefined

Please tell me:

  1. Is there any name that represents this problem
  2. What is the solution to this problem
2

There are 2 answers

0
H.Syd On BEST ANSWER

You need to put an "f" behind a float and an "l" behind a long, so that java knows what type constructor you actually want. It does not know, whether 2.33 is supposed to be a double or a float. Therefore you need to specify it in this case.

This is correct:

Test ob = new Test(1l, 2, 4.14); //fixed //Line5
Test ob1 = new Test(1, 2.33f, 4.14); //fixed //Line6
4
Mushroomator On

Numbers without any postfix are assumed to be integers. If it's a decimal number the compiler assumes it's a double so what you tell the compiler is you want to call the constructor Test(int, int, double) which does not exist.

Now if you were to have only one constructor e.g. Test(long, f, double) the compiler would automatically do the type casts for you. However, since you have many constructors, multiple conversions are possible and the compiler does not know which one to pick, hence the error message.

You now have to tell it which data types your numbers actually are.

Use L as postfix to denote a long, use F to denote a float and D to denote double.

So e.g. you could call:

  • new Test(1L, 2, 4.14) or
  • new Test(1, 2F, 4.14) or
  • new Test(1, 2D, 4.14F)
  • ...

Have a look at the Docs for Primitive data types.