I have been going through Dan Chisholm's site preparing for the
SCJP exam, and these two questions have got me stumped. Any help would be appreciated.
Quest. 1
class E {
void printS1(){System.out.print("E.printS1 ");}
static void printS2() {System.out.print("E.printS2");}
}
class F extends E {
void printS1(){System.out.print("F.printS1 ");}
static void printS2() {System.out.print("F.printS2");}
public static void main (
String args[]) {
E x = new F(); x.printS1(); x.printS2();
}}
What is the result of attempting to compile and run this program?
Answer: Prints "F.printS1 E.printS2"
This makes sense to me because an instance method (ie. printS1) is choosen based on the runtime type of the object, and static methods are invoked based on the reference type of the variable. Where I get confused is in combination with this next question.
Quest 2.
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?
Answer: Prints "A"
The reasoning behind this is that variable c1 is of type A and therefore the only method that can be called using this variable is m1(A). BUT doesn't this seem to contradict the reasoning of the previous question, where the method which is invoked is based on the runtime type of the object for instance methods - and obviously m1 is an instance method. Obviously I am missing something. Any help is appreciated. Thanks in advance.