java - Need help on a polymorphism matter -


i have simple code, want know why , how methods chosen on others :

class :

public class {     int f(a aa){         return 1;     } } 

class b :

public class b extends {     int f(a aa){         return 2;     }      int f(b bb){         return 3;     } } 

test :

public class test {     public static void main(string[] args) {         a = new a();         ab = new b();         b b = new b();          system.out.println(a.f(a));         system.out.println(a.f(ab));         system.out.println(a.f(b));          system.out.println(ab.f(a));         system.out.println(ab.f(ab));         system.out.println(ab.f(b));          system.out.println(b.f(a));         system.out.println(b.f(ab));         system.out.println(b.f(b));     } } 

now, output of program below :

1
1
1
2
2
2
2
2
3

now, can please tell me why system.out.println(ab.f(b)) gave 2 output ?

overload resolution done @ compile time. overrides used @ runtime.

this means @ compile time, compiler decides of method signatures appropriate method invocation. then, @ runtime, if method signature overridden in run-time object being used, overridden method used.

at compile time, static type of variable known. is, method signatures associated declared type of variable considered.

in case, variable ab declared a. therefore, method signatures exist in a considered call ab.f(b). f in type a f(a aa) method. call legal method signature, code generated compiler says "at point, call method f has single parameter of type a, , pass b parameter it."

when runtime comes, since ab b instance, method f has single parameter of type a overridden in it, print 2, rather 1.

contrast b.f(b). here declared type of variable b b. therefore has 2 overloads of method f - 1 b parameter , 1 a. @ compile time, knows argument b declared b. specific overload f(b bb). invocation translated "call f single parameter of type b". , @ runtime, prints 3.

the difference? @ compile time, ab of type a , f(b bb) doesn't exist in type. b of type b, , f(b bb) exists , specific overload.


Comments

Popular posts from this blog

get url and add instance to a model with prefilled foreign key :django admin -

css - Make div keyboard-scrollable in jQuery Mobile? -

ruby on rails - Seeing duplicate requests handled with Unicorn -