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?
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:
Car
class has a constructor that takes a string argument and sets the name
instance variable.Rideable
interface has a method getCar()
that returns a Car
object and takes a string argument name
.Car
constructor as a method. The correct syntax would be Car auto = new Car("MyCar");
.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
.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".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");
.