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

前端 未结 4 792
长情又很酷
长情又很酷 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:29

    You can get sometimes get around this by making your function take a parameter of Number. This is an Object which both Integer and Double inherit from, so up to the point where a Double number and an Integer number behave the same, this will work.

    Note that there is a difference between the primitives integer and double and the Objects Integer and Double. Java uses autoboxing to automatically convert between these types in function calls, etc.

提交回复
热议问题