函数重载未解决的例子

function overloading unsolved example

public class Roshni {

    void sum(int i, int j) {
        System.out.println("inside 1st i = " + i);
    }
    void sum(short i, int j) {
        System.out.println("inside 2nd i = " + i);
    }

    public static void main(String s[]) {
        Roshni r = new Roshni();
        r.sum(5, 5);
    }
}

现在我的问题是为什么即使第一个命令行参数 5 在 short 的范围内也会调用 sum(int i,int j) 而当我像这样进行类型转换时 r.sum(Short( 5),5);然后它调用 sum(short i,int j)

在 java 中,文字整数是 implicitly considered 作为 int

因此,除非您将其指定为 short(例如通过强制转换),否则就编译器而言,它是对 sum(int i,int j) 的调用。

这不是重载解析的问题 - 您使用 short 参数的方法甚至不适用。这是一个例子:

public class Test {
    public static void foo(short x) {        
    }

    public static void main(String[] args) throws Exception {
        foo(5); // Error
    }
}

这给出了一个编译时错误:

Test.java:10: error: incompatible types: possible lossy conversion from int to short
        foo(5);
            ^

整数字面量的类型是int,并且没有从intshort的正常隐式转换。现在你可以写:

short x = 5;

...因为它位于 assignment context 中,其中可以进行其他转换:

In addition, if the expression is a constant expression (§15.28) of type byte, short, char, or int:

  • A narrowing primitive conversion may be used if the type of the variable is byte, short, or char, and the value of the constant expression is representable in the type of the variable.

但是,这不适用于方法参数。

一旦您获得类型 short 的值,然后 重载解析将发挥作用:

short x = 5;
r.sum(x, 5);

现在两种方法都适用,编译器会按照JLS 15.12.2.5的规则选择第二种作为更具体的一种。

如果指定两个方法为

sum(double i,int j)
sum(short i,int j) 

现在,如果您调用 sum(12.12,4),那么将调用 sum(double i,int j)。这是因为java中的实数值或小数值是double类型。要调用 sum(short i,int j) 需要通过类型强制转换为 short 来额外指定。

sum(short(12.23),4) 

这种转换为 short 的类型将丢弃 64 位双精度值 12.23 中的高阶位,仅选择最后 16 位作为短值。