Analyze the following code. 1 public class Test { 2 public static void main(String[] args) { 3 Number[] numbers = {new Rational(1, 2), new Integer(4), new Double(5.6)}; 4 java.util.Arrays.sort(numbers); 5 } 6 }

Analyze the following code.

 1 public class Test {
 2 public static void main(String[] args) {
 3 Number[] numbers = {new Rational(1, 2), new Integer(4), new Double(5.6)};
 4 java.util.Arrays.sort(numbers);
 5 }
 6 }

A. The program has a compile error because numbers is declared as Number[], so you cannot assign {new Rational(1, 2), new Integer(4), new Double(5.6)} to it.
B. The program has a runtime error because numbers is declared as Number[], so you cannot assign {new Rational(1, 2), new Integer(4), new Double(5.6)} to it.
C. The program has a compile error because numbers is declared as Number[], so you cannot pass it to Arrays.sort(Object[]).
D. The program has a runtime error because the compareTo methods in Rational, Integer, and Double classes do not compare the value of one type with a value of another type.

The correct answer is D

Explanation: (A) and (B) are incorrect because Rational, Integer, and Double are subclasses of Number and any instances of these classes can be elements of the Number[] array. (C) is incorrect because it is fine to pass an instance of Number[] to a parameter of the Object[] type. (D) is correct because the compareTo method in Rational, Integer, Double only compare two Rational objects, two Integer objects, or two Double objects.


Java

Learn More Multiple Choice Question :