Java OCA OCP Practice Question 2314

Question

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;//w  ww . ja  va2  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 doC(Garage<?> 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 one correct answer.

  • (a) The call to the put() method in statements (1) - (2) will compile.
  • (b) The call to the put() method in statements (3) - (4) will compile.
  • (c) The assignment statement (5) will compile.
  • (d) The assignment statements (6), (7), and (8) will compile.


(c)

Note

The type of reference g is of Garage<?>.

We cannot put any object in such a garage, and can only get an Object out.

The type of value returned by the get() method in statements (6) - (8) is (capture-of ?).

Some unknown type and, therefore, not compatible for assignment to Vehicle, Car, and Sedan, as the value might turn out to be of a totally unrelated type.




PreviousNext

Related