javaexceptiontypesconstructorconstructor-overloading

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


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

Solution

  • 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