java - Why is the wrong method called: Strange inheritance behaviour -



java - Why is the wrong method called: Strange inheritance behaviour -

so question inheritance , method overriding. specifically: case when kid class has same-name method parent, different signature, like:

class has methodx(string arg) class b extends has methodx(int arg)

in normal cases right method called based on argument.

but in next code i've encountered unusual behavior can't explain:

static class { public void method1() { system.out.println("m1.a"); } public void method4(a arg) { //original method4 system.out.println("m4.a"); } } static class b extends { public void method1() { system.out.println("m1.b"); } } static class c extends b { public void method4(a arg) { //override method4 class system.out.println("m4.c"); } } static class e extends c { public void method1() { system.out.println("m1.e"); } public void method4(e arg) { //no override: same name, different method4 in class or c system.out.println("m4.e"); } } public static void main(string[] args) { va = new a(); b vb = new b(); c vc = new c(); e ve = new e(); //at point fine ve.method4(ve); //calls method4 class e based on parameter type - right ve.method4(va); //calls method4 class c based on parameter type - right //after code unusual things happen vc = new e(); vb = vc; vb.method1(); //output: m1.e; method1 class e called - right vb.method4(vb); //output: m4.c; method4 class c called - why? vc.method1(); //output: m1.e; method1 class e called - right vc.method4(vc); //output: m4.c; method4 class c called - why? vc.method4(ve); //output: m4.c; method4 class c called - why? }

so output of programm above is:

m4.e m4.c m1.e m4.c //why? expected: m4.e m1.e m4.c //why? expected: m4.e m4.c //why? expected: m4.e

the behaviour of

vb , vc

is cannot understand. ideas?

i'm guessing expected m4.e printed. don't forget overload resolution performed @ compile-time, not @ execution time.

neither c nor b have method4(e) method available, compiler resolves calls method4(a) method... isn't overridden e. calls have m4.c // why? in question calls method signature method4(a), called on instance of e. e doesn't override method4(a), it's left implementation in c, prints m4.c.

nothing unusual going on here @ all.

java inheritance method-overriding

Comments

Popular posts from this blog

Delphi change the assembly code of a running process -

json - Hibernate and Jackson (java.lang.IllegalStateException: Cannot call sendError() after the response has been committed) -

C++ 11 "class" keyword -