Java OCA OCP Practice Question 2392

Question

Which of the following options when inserted at //INSERT CODE HERE would compile successfully without any warning? (Choose all that apply.).

class Box<T> {
    T t;/*from  ww  w . j  a v  a2s. co  m*/
    Box(T t) {
        this.t = t;
    }
    T getValue() {
        return t;
    }
}
class Test {
    public static void main(String args[]) {
    //INSERT CODE HERE
    }
}
a  Box box = new Box("abcd");
b  Box<String> box = new Box<>("String");
c  Box<String> box = new Box<String>("Object");
d  Box<Object> box = new Box<String>("String");


b, c

Note

Option (a) generates a compilation warning, because it uses generic code without its type information.

Options (b) and (c) are correct.

The type that you use for declaring a variable of class Box is String, as in Box<String> box.

Class Box defines only one constructor that accepts an object of its type parameter.

Even though you can just use the angle brackets and drop the type parameter String from it, you must pass a String object to the constructor of class Box or a subclass.

The following code also compiles without warning (and I pass an instance of a subclass of the generic type parameter into the constructor):.

Box<Object> box3 = new Box<Object>("Object");

Option (d) fails to compile.

Even though class String subclasses class Object, the reference variable box of type Box<Object> can't refer to objects of Box<String>.




PreviousNext

Related