为什么带byte参数的方法调用short的方法,为什么不调用int?

Why does the method with byte parameter calls the method with short, why not int?

class Practice {
   public static void aMethod (int val) { System.out.println("int"); }
   public static void aMethod (short val) { System.out.println("short"); }
   public static void aMethod (Object val) { System.out.println("object"); }
   public static void aMethod (String val) { System.out.println("String"); }

   byte b = 9;
   Practice.aMethod(b); // first call My guess:don't know? it is short but why
   Practice.aMethod(9); // second call My guess:int correct 
   Integer i = 9;
   Practice.aMethod(i); // third call My guess: Object correct
   Practice.aMethod("9"); // fourth call My guess: String correct
}

为什么以byte(b)为参数调用的方法调用short的方法?

Java 自动为您的类型选择最适用的方法。

在这种情况下,您提供的是 byte,这是可能的最小数据类型。所有数据类型的转换如下所示:

  • int - 可能,直接从 byte 转换为 int
  • short - 可能,直接从 byte 转换为 short
  • String - 不可能,byte 不是 String(需要使用解析方法)
  • Object - 可能,从 byteByteObject
  • 的转换

Java 现在自动选择转换为 最窄的类型

Object 的转换有利于 intshort,因为它引入了一个完整的对象,这是一个巨大的开销。

最终选择 short 而不是 int,因为它 更小 byte 适合 short,它本身适合 int.

  • byte - 从 -2^(7)2^(7)-1
  • short - 从 -2^(15)2^(16)-1
  • int - 从 -2^(31)2^(31)-1

(差异较大,但你不会在图像中看到任何东西)