Java:将具有不同类型的参数传递给函数

标签 java parameter-passing implicit-conversion

在 Java 中,假设我们有一个带有参数 double a 的函数。如果我传递一个整数作为参数,它会起作用吗? (我的意思是,是否存在隐式转换?)在相反的情况下:如果我有例如一个整数作为参数,我传递一个 double ?

不幸的是,我现在无法编译我的代码,我想检查一下这个断言。 感谢您的关注。

最佳答案

参见 JLS - Section # 5.3有关方法调用转换的详细信息。

Method invocation contexts allow the use of one of the following:

- an identity conversion (§5.1.1)
- a widening primitive conversion (§5.1.2)
- a widening reference conversion (§5.1.5)
- a boxing conversion (§5.1.7) optionally followed by widening reference conversion
- an unboxing conversion (§5.1.8) optionally followed by a widening primitive conversion.

因此,根据规则 # 2,您的第一次调用(intdouble)将正常工作。

但是第二次调用(doubleint)将给出编译器错误,根据同一部分中进一步引用的语句:-

If the type of the expression cannot be converted to the type of the parameter by a conversion permitted in a method invocation context, then a compile-time error occurs.

关于Java:将具有不同类型的参数传递给函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13277655/

相关文章:

java - java和反射中对泛型的限制

java - 集成测试从 gradle build 运行而不是从 intellij 运行?

java 多个构造函数

c# - 过程需要一个未提供的参数

c++ - 强制缩小转换警告

java - 查询运行缓慢

c - 如何允许可变参数传递给函数

python - 计算有多少参数作为位置传递

c - float常量隐式转换为int类型什么时候会溢出

C# 使用 LINQ 和 Nullable Boolean