请解释一下,为什么我写了4个重载方法并调用它=>;它选择了'int'作为默认值的方法,而不是'byte',这是比较接近的,因为它可以存储-127到128的值?
class Main {
public static void method(short s) {
System.out.println("short");
}
public static void method(byte b) {
System.out.println("byte");
}
public static void method(int i) {
System.out.println("int");
}
public static void method(long l) {
System.out.println("long");
}
public static void main(String[] args) {
// put your code here
method(10);
}
}
因为 Java语言规范 说的。
科 3.10.1. 整数字 说。
一个整数字 属于
long
如果它的后缀是一个ASCII字母L
或l
(ell);否则,它 属于int
(§4.2.1).
所以你的数字文字 10
属于 int
.
这是因为默认的数字文字类型是整数。要指定长的文字,你应该在最后加上L。如果要指定字节文字,你应该在最后加上L。