我是 Java 新手,在测试一些代码时偶然发现了这一点。为什么 Java 将 x(数据类型为 long)传递到接受双参数而不是整数参数的函数中。如果有人能向我解释原因,我将不胜感激(即使对你们大多数人来说这可能是一个简单的问题!)提前谢谢!
public class Hello {
public static void main (String [] args) {
long x=1;
System.out.println("Before calling the method, x is "+x);
increase(x);
System.out.println("After calling the method, x is "+x);
System.out.println();
double y=1;
System.out.println("Before calling the method, y is "+y);
increase(y);
System.out.println("After calling the method, y is "+y);
}
public static void increase(int p) {
p+=1;
System.out.println(" Inside the method is "+p);
}
public static void increase(double p) {
p+=2;
System.out.println(" Inside the method is "+p);
} }
Run Code Online (Sandbox Code Playgroud)
调用方法时允许的转换由 JLS 第 5 章定义。隐式原始转换必须是加宽的,也就是说,不会导致幅度损失(尽管在 long 到 double 的情况下,可能会导致精度损失)。
有六种转换上下文,其中 poly 表达式可能受上下文影响或可能发生隐式转换。每种上下文对于 poly 表达式类型都有不同的规则,并且允许在上述某些类别中进行转换,但不允许在其他类别中进行转换。上下文是:
...
严格调用上下文(第 5.3 节、第 15.9 节、第 15.12 节),其中参数绑定到构造函数或方法的形式参数。可能会发生扩大原语、扩大引用和未经检查的转换。
松散调用上下文(第 5.3 节、第 15.9 节、第 15.12 节),其中,与严格调用上下文一样,参数绑定到形式参数。如果仅使用严格调用上下文无法找到适用的声明,则方法或构造函数调用可能会提供此上下文。除了扩大和未经检查的转换之外,此上下文还允许进行装箱和拆箱转换。
从 long 到 int 的转换是一种缩小原始转换,因为它可能会导致大小信息的丢失。所以它不会被调用,除非你首先显式地转换为(int).