Java:将具有不同类型的参数传递给函数 [英] Java: passing an argument with a different type to a function

查看:746
本文介绍了Java:将具有不同类型的参数传递给函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Java中,假设我们有一个参数为double a的函数.如果我将整数作为参数传递,是否可行? (我的意思是,是否存在隐式转换?)而在相反的情况下:如果我有一个整数作为参数,并且我传递了一个双精度值?

In Java, suppose we have a function with the parameter double a. Does it work if I pass an integer as argument? (I mean, is there an implicit conversion?) And in the opposite case: if I have e.g. an integer as parameter, and I pass a double?

很不幸,目前我无法编译我的代码,我想检查一下这个断言. 谢谢您的关注.

Unluckily, I am not able to compile my code at the moment, and I would like to check this assert. Thank you for your attention.

推荐答案

请参见

See JLS - Section # 5.3 for details on Method Invocation Conversion.

方法调用上下文允许使用以下之一:

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.

因此,您的第一次调用(intdouble)将根据规则2 正常运行.

So, your first invocation(int to double) will work fine according to rule # 2.

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

But the second invocation(double to int) will give Compiler Error, according to the statement quoted further in the same section: -

如果表达式的类型不能转换为表达式的类型 通过方法调用上下文中允许的转换来设置参数, 那么就会发生编译时错误.

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:将具有不同类型的参数传递给函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆