开发者

I removed a necessary constructor, yet it still compiles and runs

Whilst tidying up my project by removing what I believed to be unnecessary code, I removed a constructor of the form

public MyClass(int a,  int b) 

leaving in place the other constructor

public MyClass(double c, double d)

There was a call t开发者_Go百科o the int, int constructor which I hadn't noticed, yet it compiled and ran but invoked the double, double version, quite properly causing an exception handler I had written to be thrown. MyClass doesn't extend any other class.

By what rules does Java cause this invisible automatic cast to happen?


By this rule: http://java.sun.com/docs/books/jls/third_edition/html/conversions.html#5.1.2

It's a widening conversion.


This is a Widening Primitive Conversion. Since you can convert an int to a double without losing any information, the Java language performs this invisibly.


In methods overloading, the most specific method is called, so if you have foo(int, int) and foo(double, double) and you call foo(1,2) then foo (int, int) will be called. but since 1, 2 may be doubles as well, if you don't have foo(int, int), foo(double, double) will be called.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜