Java – why does type promotion take precedence over varargs of overloaded methods
•
Java
public class Test
public class Test { public static void printValue(int i,int j,int k) { System.out.println("int"); } public static void printValue(byte...b) { System.out.println("long"); } public static void main(String... args) { byte b = 9; printValue(b,b,b); } }
The output of the above code is "int" But it should be "long" because the byte type parameter function already exists But the program here is promoting the byte value to int, but this is not the case
Can anyone clarify what happened here?
Solution
In the case of overloaded methods, the variable parameter method will always be the last method selected by the compiler Promoting bytes to int (extended conversion) takes precedence over methods that take var Arg parameters
The reason behind this is that languages need backward compatibility Older features will take precedence over newer features A simple way to understand JLS's statement about variable parameters is to expand will beat boxing and boxing will beat var args
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码