最终铸造概念不适用于重载

final casting concept doesn't apply for overloading

在我的选角class中,老师教了我们一个有趣的事实

class Casting {
    public static void main(String args[]){
        int i = 10;
        byte b = i;
        System.out.println(b);
    }
}

我们遇到错误

java:5: possible loss of precision

然后我们改代码如下

class Casting1 {
    public static void main(String args[]){
        final int i = 10;
        byte b = i;
        System.out.println(10);
    }
}

10

我们得到了正确的输出。至于原因,他告诉我们,当我们修改一个变量final时,这个变量是以尽可能小的数据类型存储的。在这种情况下是 byte。这就是我们能够在不使用 cast 关键字的情况下进行转换的原因。

但是当我们这样使用方法重载时,

class A {
    void m(int i){
        System.out.println("int");
    }
    void m(byte b){
        System.out.println("byte");
    }
    public static void main(String args[]){
        A a1 = new A();
        final int i = 10;
        a1.m(i);
    }
}

我得到输出 int。如果最终变量存储在尽可能低的数据类型中,则应为byte。所以我在没有重载的情况下尝试了以下代码。

class A {
    void m(byte b){
        System.out.println("byte");
    }
    public static void main(String args[]){
        A a1 = new A();
        final int i = 10;
        a1.m(i);
    }
}

java:9: m(byte) in A cannot be applied to (int)

这是什么原因?我有什么误解吗?

Is there any point that I have misunderstood?

是的。搜索应用哪种方法取决于参数的类型。与赋值的情况不同,方法参数没有转换尝试(至少,在自动装箱被添加到语言之前没有,这增加了另一组任意规则)。

您混淆了变量及其类型的记忆 space。 调用方法 m(...) 将首先检查参数变量的类型。这里是一个 int 所以它会选择相应的重载方法,不管 int 在内存中的大小。

虽然我真的很感谢你第一个将光线带入最终标识符的特征之一的例子。

如果转换是赋值的一部分,并且值可以放入 byte,编译器会自动为您执行转换。

JLS 清楚地解释了这是一种特殊情况,仅适用于 赋值 而不适用于其他上下文中的转换。

值得一提的是,byte 只有在为嵌入式设备编程或处理 files/networks 时才有用。 byteint 占用相同的 space 因为变量地址是对齐的。

这一点不太正确...

"As for the reason, he told that when we modify a variable final the variable is stored in the smallest data type possible. In this case was a byte."

它没有将它存储为一个字节,而是将它存储为一个 int,但它实际上是一个常量,因此当 Java 编译行 byte b = i; 时,它肯定知道该值将是 10,不需要转换。