this snippet is from book A Programmer's Guide to
Java SE 8 Oracle Certified Associate (OCA) by Khalid A. Mughal , Rolf W Rasmussen
public class MyClass {
public static void main(
String[] args) {
MyClass a;
MySubclass b;
a = new MyClass(); // (1)
b = new MySubclass(); // (2)
a = b; // (3)
b = a; // (4)
a = new MySubclass(); // (5)
b = new MyClass(); // (6)
}
}
class MySubclass extends MyClass {}
question : which lines cause compilation fail
my answer that was wrong : only line 6
correct answer : lines 4 and 6
what i thought was that line 4 will throw classcastexception because classes are in the same inheritance tree and compiler is not that smart to define whether under the superclas's reference a is a subclass object ( there might be ) or superclass object and has to allow assigning a reference to b and at runtime it will become clear that under a was superclass object and it ill throw an exception .
I remember doing similar questions and it was correct way of thinking so why it failed here ?