aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Could any one of you explain me this code Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Could any one of you explain me this code" Watch "Could any one of you explain me this code" New topic
Author

Could any one of you explain me this code

Mukund Pande
Greenhorn

Joined: May 21, 2003
Posts: 5
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 {
public static void main(String[] args) {
A a1 = new A();
B b1 = new B();
C c1 = new C();
A c2 = new C();
c2.m1(a1);
c2.m1(b1);
c2.m1(c1);
}
}
I feel the answer should be ABC, but actually it prints AAA
Dan Chisholm
Ranch Hand

Joined: Jul 02, 2002
Posts: 1865
Welcome to the JavaRanch Mukund!
The object referenced by c2 is of type A and does not have the overloaded methods declared in classes B and C. Therefore, method A.m1 is invoked in all three cases.
[ May 21, 2003: Message edited by: Dan Chisholm ]

Dan Chisholm<br />SCJP 1.4<br /> <br /><a href="http://www.danchisholm.net/" target="_blank" rel="nofollow">Try my mock exam.</a>
Anupam Sinha
Ranch Hand

Joined: Apr 13, 2003
Posts: 1088
Hi Mukund
Well I guess that this question is from Dan and who better than Dan to answer it. But I will give it a try.
What's actually is happening is you have an object of type A which is the superest(my word) simply the supermost class(except ofcourse Object). So when you pass in a variable of type A the compiler calls a method from class C which takes in a object of A. The class C has A's m1()method inherited(but not overriden because of different parameter types) so it calls it.
To put it simply it is a inherited method of class C that is being invoked and hence the output.
Clear now?
[ May 21, 2003: Message edited by: Anupam Sinha ]
Ryan Wilson
Ranch Hand

Joined: Apr 16, 2003
Posts: 65
The way that I look at this is.
Overloaded methods are determined at compile time.
Overriden methods are determined at runtime.
In the case above, the methods are overloaded and not overriden.
The reference type is used at compilation
The instance type is used at runtime.
(reference) (instance)
A c2 = new C();
Because the methods are overloaded (and determined at compile time), the compiler uses the reference type (in this case A) to determine what overloaded method to call.
Someone please correct me if my way of thinking is wrong!
Mukund Pande
Greenhorn

Joined: May 21, 2003
Posts: 5
Thanks a lot for the overwhelming response.
Now I am comfortable about this concept.
Thanks
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Could any one of you explain me this code