OCP Question 58, Explanation

Given:

public class B implements A {
    public String toString() {
        return "B ";
    }
    public static void main(String[] args) {
        C myC = new C();
        B myB = myC;
        A myA = myB;
        System.out.print(myB);
        System.out.print((C) myB);
        System.out.print(myA);
    }
}
class C extends B {
    public String toString() {
        return "C ";
    }
}
interface A {
    public String toString();
}

What is the result?

A. B B B
B. B C B
C. C C B
D. C C C
E. The code throws a ClassCastException

 

The correct answer is D.

 

This Problem is so simple we don’t even need to draw pictures or apply the castype-related rule (ref.to Nailing 1Z0-809, page 312, if you are unsure what castype stands for). It is sufficient to observe that all three assignment LOCs in B are dealing with the same object whose actype is C. It follows, therefore, that there can be no ClassCastException at (C)myB in the second sout despite the fact that B is wider than C, and since calls to toString() are all virtual (because the methods are non-static, non-private and non-final) , every time a printing stat fires, the toString() in C runs.

Leave Comment

Your email address will not be published. Required fields are marked *