Java SE 8 Programmer II Exam: Create an Instance of Car

Create an Instance of Car

Question

Given: interface Rideable{Car getCar (String name);} class Car { private String name; public Car (String name) { this.name = name; } } Which code fragment creates an instance of Car?

Answers

Explanations

Click on the arrows to vote for the correct answer

A. B. C. D.

C.

The correct answer is option C. Rideable rider = Car :: new; Car vehicle = rider.getCar("MyCar");

Explanation:

  • The Car class has a constructor that takes a string argument and sets the name instance variable.
  • The Rideable interface has a method getCar() that returns a Car object and takes a string argument name.
  • Option A is not valid syntax as it is trying to call the Car constructor as a method. The correct syntax would be Car auto = new Car("MyCar");.
  • Option B creates an instance of Car using a constructor reference, but does not use it to create an instance of Car. Instead, it tries to call getCar() on the auto object, which is not possible as auto is an instance of Car and not Rideable.
  • Option C creates an instance of Car using a constructor reference and assigns it to a Rideable reference variable rider. It then calls getCar() on rider to create a Car object with the name "MyCar".
  • Option D is not valid syntax. The correct syntax to create an instance of Rideable would be to use a lambda expression or method reference. Rideable rider = name -> new Car(name); or Rideable rider = Car::new;. It then tries to call getCar() on the Rideable class, which is not possible as getCar() is not a static method.

Therefore, the correct answer is option C. Rideable rider = Car :: new; Car vehicle = rider.getCar("MyCar");.