Program 1 class AA
{
}
class BB extends AA
{
}
class casting
{
public static void main(
String arg[])
{
AA a=new AA();
BB b=new BB();
AA c=new BB();
b = (BB) a; //line 1
a = b ;
b = (BB) c;
c = b;
}
}
when I run this program it is compiling fine,but throwing an exception stating that
"AA cant not be cast to BB" Look at another one:
Program 2
class parent
{
}
class castingTest extends parent
{
public static void main(String ar[])
{
parent p=new parent();
castingTest c=new castingTest();
p=c;
c=(castingTest)p;//Line A
}
}
Where as this is not causing any problem.
My doubt is in
program 1 above,
line 1 is not a problem,as it is downcasting,casting is done properly when assigning a reference of superclass to a subclass reference.
But why it is throwing a runtime exception?
Why it is not the case with second program?
In this
"Line A" too doing the same(Down casting)but running without any Exception.
Please clear my doubt