Doubts posted below code snippet:
class A {}
class B extends A{}
public class MyClass
{
public static void main(
String args[]){
A a = new A();
B b = new B();
a = b ; // 1.... typical upcasting
b =(B)a; // 2.. typical downcasting
a = new A(); //3...assigning new reference of Type A
b =(B)a; // 4...compiles but throws CCE at runtime
}
}
i> Here at 1 we assign reference of type B to a reference of Type A. Hence the Type A object reference (a) now points to an address which contains an object of type B. At 2 we are going reverse. Now, after executing step 1 why does the compiler require an explicit cast at 2 ?
ii> At 3 we are creating a new instance of A and assigning it to a B type reference at 4. While the compiler doesn't complain at 4 but the runtime throws up a ClassCastExcp. How can the compiler allow something which the runtime flatly rejects?
iii> Why should I use downcasting in any scenario since in the end game I am only getting a reference to a Type B object(same or different) using a Type B object? Since through inheritence I am already accessing all the members of my superclass I donot need to use downcasting at all. Please highlight any scenario where we cannot do w/o downcasting at all.
Thanks in Advance for sharing your valuable time. I have made the doubts as legible and intelligible as possible.