What will be the result of attempting to compile the following code?
class Vehicle { } class Car extends Vehicle { } class Sedan extends Car { } class Garage<V> { private V v;/*from ww w . ja v a 2 s . c o m*/ public V get() { return this.v; } public void put(V v) { this.v = v; } } public class Main { private Object object = new Object(); private Vehicle vehicle = new Vehicle(); private Car car = new Car(); private Sedan sedan = new Sedan(); public void doB(Garage<Car> g) { g.put(object); // (1) g.put(vehicle); // (2) g.put(car); // (3) g.put(sedan); // (4) object = g.get(); // (5) vehicle = g.get(); // (6) car = g.get(); // (7) sedan = g.get(); // (8) } }
Select the two correct answers.
put()
method in statements (1) - (2) will compile.put()
method in statements (3) - (4) will compile.(b) and (c)
The type of reference g is of Garage<Car>.
We can put a Car in such a garage and get a Car out.
The type of value returned by the get()
method in statement (8) is Car and, therefore, not compatible for assignment to Sedan.