polymorphism - Is there any reason that Java uses late/static binding for overloaded methods in the same class? -
is there specific reason why java uses binding overloaded methods? wouldn't possible use late binding this?
example:
public class someclass { public void dosomething(integer i) { system.out.println("integer"); } public void dosomething(object o) { system.out.println("object"); } public static void main (string[] args) { object = new integer(2); object o = new object(); someclass sc = new someclass(); sc.dosomething(i); sc.dosomething(o); } }
prints: object object
i rather expect: integer object
it seems me obvious reason allows compiler guarantee there function called.
suppose java chose function based on run-time type, , wrote this:
public class myclass { public void foo(integer i) { system.out.println("integer"); } public void foo(string s) { system.out.println("string"); } public static void main(string[] args) { object o1=new string("hello world"); foo(o1); object o2=new double(42); foo(o2); } }
what's output? first call foo presumably prints "string", second call has go. suppose generate run-time error. similar argument of strictly-typed versus loosely-typed. if chose function @ run time, more flexible in sense. choosing function @ compile time, error messages @ compile time rather having wait until run time , sure have exercised every possible path every relevant combination of data.
Comments
Post a Comment