Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Dan's questions : overloading

 
Kristof Camelbeke
Ranch Hand
Posts: 97
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Question 23
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 c1 = new C(); C c2 = new C(); c1.m1(c2);
}}
What is the result of attempting to compile and run the program?
a. Prints: A
b. Prints: B
c. Prints: C
d. Compile-time error
e. Run-time error
f. None of the above
Answer is : prints A
I thought it was C because I've read that with overloading the compiler looks at the reference to see what method should be invoked..
c1.m1(c2);
Here the reference c2 is of type C so the compiler will invoke the method in class C, no ?
I thought that it was during overiding that the Object type was looked at during runtime but here we are talking about overloading methods... Guess I'm confused...
 
Dan Chisholm
Ranch Hand
Posts: 1865
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Kristof,
The reference type of c1 is A, and type A only declares one method named m1. The methods that overload method name m1 are declared in classes B and C, but those methods can not be invoked using a reference of type A.
 
Kristof Camelbeke
Ranch Hand
Posts: 97
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ok Dan I got it ! Thanks
One more question concerning this :
Would it be answer c if class A had overloaded methods m1 with types B & C ?
Kristof
 
Alfred Kemety
Ranch Hand
Posts: 279
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes Kris, you can try it with the code as well.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic