Which statement, when inserted at the indicated position in the following code, will cause a runtime exception?
class A {}
class B extends A {}
class C extends A {}
public class Q3ae4 {
public static void main(String[] args) {
A x = new A();
B y = new B();
C z = new C();
// Insert statement here
}
}
Select the one correct answer.
x = y;
z = x;
y = (B) x;
z = (C) y;
y = (A) y;
Soln
(c)
Statement (a) will work just fine, and (b), (d), and (e) will cause compilation errors. Statements (b) and (e) will cause compilation errors since they attempt to assign an incompatible type to the reference. Statement (d) will cause compilation errors since a cast from B to C is invalid. Being an instance of B excludes the possibility of being an instance of C. Statement (c) will compile, but will throw a runtime exception since the object that is cast to B is not an instance of B.
------------------------------------------------------------------------------------------------------
I never understand upcasting and downcasting concepts. Man this is weird. Is there any general tutorial that can help me with it...
Regards,
http://www.beginner-java-tutorial.com
Hemanth