Java implicit methods/parameters?
implicit, java, parameters
Solution
Think about this piece of code:
whatsInTheGarage().drive();
as a shorthand for this:
Car returnedCar = whatsInTheGarage();
returnedCar.drive();
Is it clear now? All C-like languages with c-like syntax behave like this.
UPDATE:
myCar.drive(); //call method of myCar field
Car otherCar = new Car();
otherCar.drive(); //create new car and call its method
new Car().drive() //call a method on just created object
public Car makeCar() {
return new Car();
}
Car newCar = makeCar(); //create Car in a different method, return reference to it
newCar.drive();
makeCar().drive(); //similar to your case
Problem
im currently reading a book about programming Android and there is a nice little reference guide on Java in the beginning chapters. However, I stumpled upon something about implicit parameters that I did not quite understand. He defines the class Car: ``` public class Car { public void drive() { System.out.println("Going down the road!"); } } ``` Then he continues on with this: ``` public class JoyRide { private Car myCar; public void park(Car auto) { myCar = auto; } public Car whatsInTheGarage() { return myCar; } public void letsGo() { park(new Ragtop()); // Ragtop is a subclass of Car, but nevermind this. whatsInTheGarage().drive(); // This is the core of the question. } } ``` I just want to know how we can call drive() from the class Car when JoyRide is not an extension of Car. Is it because the method whatsInTheGarage() is of return type Car, and thus it "somehow" inherits from that class? Thanks.