this was previously posted by samy venkat...I want clarification on how the methods were chosen
My assumptions are Class A has 3 overloaded methods... Class B has 2 overloaded methods m1(A a) and m1(C c) that it inherits from A and 1 overidden method m1(B b) Class C has 1 method inherited from A, 1 method inherited from B and 1 overidden method in C So what happens at line 1 and line 2
line 1: c1 is of type A and class A has a method m1 which takes parameter of type A- void m1(A a); Now c2 is also of type A therefore c.m1(C2) matches the method void m1(A a);compiler then looks to see if this method has been overridden down the tree.Nope! so print AA. Line 2: C1 is again type A but b1 is of type b.We have a matching method in class A -void m1(B b)!But hang on a sec..this is overridden in the child class B.. we have a method there too called void m1(B b).Is this further overridden down the tree too?No. Ok then print B as per this method in Class B. Job finished.
Hi Preeti At line 1 class C's method is being invoked as it has inherited that method from A. Or you can simply say that class A's method is being invoked. On line class C's method is being invoked which it inherited from B. Though B also inherited the method from A but now that B has overriden it B's method would be inherited by class C. So basically its class C's method that are being invoked.
Hi, c1.m1(c2); // line 1 c1.m1(b1); // line 2 On line 1, c1 is an instance of type A which has an actual object of C. c1 calls method named m1. Class A, B and C all have method m1. Differences are arguments. m1 in class A has all variety of arguments. m1 in class B has argument of type B. m1 in class C has an argument of type C. Since line 1 is passing an arugument of type A, only possible method that can respond to is m1 in class A. On line 2, c1 is again type A of object C. The argument passed is b1, which is an instance of type B that has actual object of B. So when you look at the arguments list, there are two m1 methods that accept type B object. Ones in class A and ones in class B. Which one to choose? Since m1 method in class B has exactly same name and argument type as that of class A, m1 in B is overriding m1 in A. Thus, it choose m1 in class B. Therefore out put should be AA,B.
"If anything can go wrong, it will"
The only cure for that is hours of television radiation. And this tiny ad:
RavenDB is an Open Source NoSQL Database that’s fully transactional (ACID) across your database