Which statement about the program is true?.
class MyClass {}// ww w . j a v a 2 s . c om class MyClass2 extends MyClass {} // Filename: MyClass.java public class MyClass { public static void main(String[] args) { MyClass[] arrMyClass; MyClass2[] arrMyClass2; arrMyClass = new MyClass[10]; arrMyClass2 = new MyClass2[20]; arrMyClass = arrMyClass2; // (1) arrMyClass2 = (MyClass2[]) arrMyClass; // (2) arrMyClass = new MyClass[10]; arrMyClass2 = (MyClass2[]) arrMyClass; // (3) } }
Select the one correct answer.
(c)
The program will throw a java.lang.ClassCastException in the assignment at (3), when run.
The statement at (1) will compile, since the assignment is done from a subclass reference to a superclass reference.
The cast at (2) assures the compiler that arrMyClass
will refer to an object that can be referenced by arrMyClass2
.
This will work when run, since arrMyClass
will refer to an object of type MyClass2[].
The cast at (3) will also assure the compiler that arrMyClass
will refer to an object that can be referenced by arrMyClass2
.
This will not work when run, since arrMyClass
will refer to an object of type MyClass[].