I'm studying for an exam and I need some help to understand what is going on in the following snipped of code.
class A {
public void method1(A X) {
System.out.println("A");
}
}
class B extends A {
public void method2() {
System.out.println("B");
}
}
class C extends B {
public void method1(A x) {
System.out.println("C");
}
}
class D extends C {
public void method1(D x) {
System.out.println("D");
}
}
public class test {
public static void main(String[] args) {
C c = new D();
B b = c;
c.method1(c); // prints C
b.method1(b); // prints C
}
}
Ok this is what I think: c.method1(c) invokes method1 in C and not method1 in D because c is decleard as a C therefore method1 in D is not visible. But b.method1(b) is more difficult. B does not have method1 and I assumed that method1 in the superclass will be used, but it is not. Why is it using the method in C? I put a new D in b but nothing of the specialization of D is visable, because b is from the type B.