Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Could any one of you explain me this code

 
Mukund Pande
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 1865
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
Anupam Sinha
Ranch Hand
Posts: 1090
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 65
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks a lot for the overwhelming response.
Now I am comfortable about this concept.
Thanks
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic