java - Overloaded method selection based on the parameter's real type -


i'm experimenting code:

interface callee {     public void foo(object o);     public void foo(string s);     public void foo(integer i); }  class calleeimpl implements callee     public void foo(object o) {         logger.debug("foo(object o)");     }      public void foo(string s) {         logger.debug("foo(\"" + s + "\")");     }      public void foo(integer i) {         logger.debug("foo(" + + ")");     } }  callee callee = new calleeimpl();  object = new integer(12); object s = "foobar"; object o = new object();  callee.foo(i); callee.foo(s); callee.foo(o); 

this prints foo(object o) 3 times. expect method selection take in consideration real (not declared) parameter type. missing something? there way modify code it'll print foo(12), foo("foobar") , foo(object o)?

i expect method selection take in consideration real (not declared) parameter type. missing something?

yes. expectation wrong. in java, dynamic method dispatch happens object method called on, not parameter types of overloaded methods.

citing java language specification:

when method invoked (§15.12), number of actual arguments (and explicit type arguments) , the compile-time types of arguments used, @ compile time, determine signature of method invoked (§15.12.2). if method invoked instance method, actual method invoked determined @ run time, using dynamic method lookup (§15.12.4).


Comments