Java: passing an argument with a different type to a function

前端 未结 4 796
长情又很酷
长情又很酷 2020-12-06 11:50

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 i

4条回答
  •  一个人的身影
    2020-12-06 12:25

    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.
    

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

    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.

提交回复
热议问题