Please explain me below situation
What would be the output?
interface A{}
class B implements A{}
class C extends B{}
class D extends C{}
class E extends D{
public static void main(String args[]){
C c = new C();
B b = c;
A a = (E)c;
a = (B)c;
c = (C)(B)c;
}
}
Being completely strict, that’ won’t compile because in line 4 you type
Classinstead ofclassAnd later you define twice
aandcNow assuming those were typos the output would be
ClassCastExceptionbecauseccan’t be casted toE.When you perform a cast is like you were saying: “I’m the programmer and I know this is a…”
____(put your class here)And the compiler will allow you compile.But if in runtime the instance is not really a ____ ( an
Ein this case, which is not ) then it will throwClassCastException.The program won’t fail with
A a = ( B ) c; becausecis an instance ofCwhich is a subclass ofB.You can say that,
Cis aB. To understand it better think on the following declaration:Every
Employeeis anObjectso the cast will succeed, actually is it so clear that it will succeed that you don’t even need to put the cast operator().But not necessarily an
Objectis anEmployee.That’s why
A a = ( E ) c;fail, because, the referencecwas not created as anEI hope that helps.