Given the following code, which of the numbered lines should be commented, to have the code compile and run successfully? Select the appropriate line numbers.

class Parent { }
class Child extends Parent { }
class Child2 extends Parent { }  

public class ArrayTest {
    public static void main(String[] args) {
        Parent[] arr1 = new Child[3];
        arr1[0] = new Parent(); //1
        arr1[1] = new Child();  //2
        arr1[2] = new Child2(); //3
        arr1[3] = new Child();  //4

        Child2[] arr2 = {new Child2(), new Child2(), new Child2()};
        add(arr2);
    }

    public static void add(Parent[] arr) {
        arr[0] = new Parent(); //5
        arr[1] = new Child();  //6
        arr[2] = new Child2(); //7
        arr[3] = new Child2(); //8
    }
}
Explanation
Lines 4 and 8 will throw an ArrayIndexOutOfBoundsException (the last index for an array of size 3 is 2) Lines 1 and 5 will throw an ArrayStoreException, since an array of a subclass type can not store an object of superclass type. (The opposite would work though). Lines 3 and 6 will also throw an ArrayStoreException, since Child and Child2 class types are not each others subtypes.

Слідкуй за CodeGalaxy

Мобільний додаток Beta

Get it on Google Play
Зворотній Зв’язок
Продовжуйте вивчати
тести з Java
Cosmo
Зареєструйся Зараз
або Підпишись на майбутні тести