Well pardners, I need some help with Dan's Chapter 6, exam 1, question 8.
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();
A c2 = new C();
A c3 = new C();
C c4 = new C();
c1.m1(c4);
c2.m1(c4);
c3.m1(c4);
}
}
What is the result of attempting to compile and run the program?
a. Prints: AAA
b. Prints: ABC
c. Prints: CCC
d. Compile-time error.
e. Run-time error.
f. None of the above
My thinking for the code line: c1.m1(c4);
I know that the true class is of type C and I need to match the method from it and not use the method from the reference type. I therefore answered that the code would print CCC. With anticipation of success, I headed out to verify that I got the correct answer. But Nooooooooo (insert sound clip for shootout at the OK coral) the answer is not CCC but AAA.
I went back to my notes and text books and all had examples of
polymorphism similar to the following:
class A {
void m1() {System.out.print("A");}
}
class B extends A {
void m1() {System.out.print("B");}
}
class C extends B {
void m1() {System.out.print("C");}
}
class D {
public static void main(String[] args) {
A c1 = new C();
A c2 = new C();
A c3 = new C();
C c4 = new C();
c1.m1();
c2.m1();
c3.m1();
}
}
This is just Dan's example with each method taking no arguments. This compiles and will print CCC.
Now good citizens and sheriffs of
Java Ranch (heck I will even take an answer from the villian Dan himself :-) ) I need some clarification on polymorphism. I looked at Dan's remarks for the question and I can not understand how it works (I've included his remarks below). Comparing the two examples, how is the "normal" example of polymorphism different than Dan's question?
I will sit at the bar drinking the unbearable swill they serve here and await your answers. Thanks.
Dan's remarks to question 8:
Class A has only one implementation of method m1. Class B overloads method m1 with a second implementation. Class C overloads method m1 with a third implementation. Even though c1, c2 and c3 are all instances of class C, the reference type is always A so the overload methods declared in the subclasses are not accessible. For that reason, the implementation of method m1 declared in class A is always invoked.