class A { void m1(A a) { System.out.print("A"); } } class B extends A { void m1(B b) { System.out.print("B"); } } class C extends B { void m1(C c) { System.out.print("C"); } } class D extends C { void m1(D d) { System.out.print("D"); } public static void main(String[] args) { A a1 = new A(); B b1 = new B(); C c1 = new C(); D d1 = new D(); d1.m1(a1); //1 d1.m1(b1); d1.m1(c1); } }
Here the Output is ABC The doubt is when d1.m1(a1) //1 is called .....then the method in D class should be called. Why is it calling method in class A?
agrah upadhyay
Ranch Hand
Joined: Sep 01, 2005
Posts: 579
posted
0
Here the Output is ABC The doubt is when d1.m1(a1) //1 is called .....then the method in D class should be called. Why is it calling method in class A?
Class D is extending class C which extending to B which further extending to class A.Means class D is AVAILABLE with methods:void m1(A a) ,void m1(B b),void m1(C c),void m1(A a) . Now based upon method argument call,method invokation is resolved. Got It?
<i>--Agrah Upadhyay--</i><br />Final Year B.Tech SCJP,SCWCD,SCBCD <br /> <br /><b>Now since the real test for any choice is having to make the same choice again,knowing full well what it might cost.</b>-Oracle
Andreas Sandberg
Ranch Hand
Joined: Sep 14, 2005
Posts: 31
posted
0
Ooops I almost confused myself with this problem. I think you're under the impression that what is happening here is that the method is being overridden but if you look closely you will see that the argument list does not exactly match. Each subclass modifies the argument list ever so slightly. So D actually has all of the methods from class A,B, and C. It would be no different than if you did this.
So c.m1(3,3) will call the method that was defined in class B. The same is true for your example except the argument list is a single object but not the same object so overriding does not take place.
"When the compilers not happy ain't nobody happy"
A Kumar
Ranch Hand
Joined: Jul 04, 2004
Posts: 973
posted
0
Hi ,
Whats the explanation for this??
c1.m1(d1);
Output: C
Tx
agrah upadhyay
Ranch Hand
Joined: Sep 01, 2005
Posts: 579
posted
0
posted September 28, 2005 03:56 AM Hi ,
Whats the explanation for this??
c1.m1(d1);
Output: C
My previous post should explain it.For class C only 3 overloaded versions are available:m1(A a),m1(B b),m1(C c).Now c1 is an instance of class C.So compiler has to resolve what function to be called in invocation c1.m1(d1); .Now compiler has to choose more specific method with respect to argument .Remember C is direct superclass of D.so output will be C means m1(C c) has been called.