Java implicit methods / parameters?
im currently reading a book about android programming and there is a little little Java reference guide in the early chapters. However, I stumbled upon something about implicit parameters that I didn't quite understand.
It defines the class Car :
public class Car {
public void drive() {
System.out.println("Going down the road!");
}
}
Then he continues:
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 Car class when JoyRide is not a Car extension . Is this because the whatsInTheGarage () method has a return type of Car , and thus it inherits "somehow" from that class?
Thank.
source to share
Think about this piece of code:
whatsInTheGarage().drive();
as a shorthand for this:
Car returnedCar = whatsInTheGarage();
returnedCar.drive();
It is now clear? All C-likelanguages with c -like syntax behaves 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
source to share
In line
whatsInTheGarage().drive()
You are calling a method drive
on the object returned from whatsInTheGarage
. The fact that JoyRide
itself is not related to Car
is irrelevant here, because you are not trying to call drive
on an object JoyRide
. Since it whatsInTheGarage
returns a Car
and you are calling the drive
object returned from whatsInTheGarage
, this will call drive
on the object Car
; in particular Car
, the returned one whatsInTheGarage
. This has nothing to do with inheritance - instead, you simply call a method on an object that is of the type of the class that specifically declares that method.
Hope this helps!
source to share