ok. first let me say that u can post this message in the programmer certification study as ull get there better answer than mine
now for my answer:
1. a reference of the parent can always refer to an object of one of the sublasses(the child).
you dont need to use the (A) casting as it work without - upcasting is done automatically.
it will compile and run fine.
2. for downcasting (parent to child) u need to write the cast yourself, so u were correct to write (B) .
now for the tricky part, during compilation it will ALWAYS compile because when the compiler compiles it ONLY checks to see if the child (in this case B) is subclass of parent (A).
BUT in runtime (while the program runs) in this case it will throw an error. the reason for this is because at runtime a1 doesnt actually refer to (points to) an instance of B.
3. same goes here as 2! it will always compile (y is subclass of X) - u have to use explict cast (parent to child) BUT at runtime again it will throw error cause myX doesnt refer at runtime to an instance of Y.
4. compile and run fine, no casting is needed like in 1 (upcasting child to parent).
i will add another option to demonstarte some more:
5. class Y extends X
X myX=new Y(); //myX can refer to an
instance of Y (upcasting)
Y myY=(Y)myX;
this will compile ( u need to explict casting ) BUT it will also work fine in runtime (NO exception) cause at runtime myX actually refer to an instance of Y.
phew!
hope i made it less messier, like i said im not that good in explaining
