Sunday 15 January 2012

Why does polymorphism not work with overloaded methods in Java? -



Why does polymorphism not work with overloaded methods in Java? -

i have basic understanding of how method overriding , overloading works in java. question why compiler searches specific method based on compile type of argument? in other words, why searches based on type of reference , not type of object in case of method overloading?

check illustration below

class base of operations { } class derived extends base of operations { } class test { void foo(base thing) { system.out.println("foo(base)"); } void foo(derived thing) { system.out.println("foo(derived)"); } public static void main(string[] args) { test tester = new test(); base of operations base = new base(); tester.foo(base);// 1st phone call base of operations = new derived(); tester.foo(base); // 2nd phone call tester.foo(new derived()); // 3rd phone call } }

actual output

1st call: foo(base) 2nd call: foo(base) 3rd call: foo(derived)

output expecting

1st call: foo(base) 2nd call: foo(derived) 3rd call: foo(derived)

1) overloading happens @ compile time i.e method definition execute decided @ compile time. 2) assigning derived class object reference base of operations class object @ run time. 3) not known @ compile time reference base of operations class object have in future i.e @ run time. 4) reason why compiler looks @ type of reference in case of method overloading

java polymorphism method-overloading

No comments:

Post a Comment