Search code examples
javaexceptiontypesconstructorconstructor-overloading

Constructor parameter with byte, short and int throwing error


I am trying to implement constructor overloading by using byte, short and long together. I am passing three values from main method and want to check which constructor gets called Test(byte, short, int) or Test(int, byte, short).

CODE:

import java.util.*;

public class Test {
    
    public Test(byte b, short s, int i) { //Line1
        System.out.println("b s i");
    }
    
    public Test(int i, byte b, short s) { //Line2 
        System.out.println("i b s");
    }
    
    public static void main(String[] args) {
        Test ob = new Test(1, 2, 3); //showing compilation error //Line3
    }
}

OUTPUT:

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

Please tell me why its happening and what is the solution to this problem.


Solution

  • The default type of a whole number constant in Java is int. When you write new Test(1, 2, 3) you tell the compiler to looks for a constructor that takes three integers as parameters, which does not exist. That's exactly what the error message says.

    You need to cast the parameters to explicitly define which constructor you want to call: new Test(1, (byte) 2, (short) 3).