yac*_*ack 3 java parameters implicit
我正在阅读一本关于Android编程的书,在开头的章节中有一篇关于Java的小参考指南.但是,我对一些我不太了解的隐式参数进行了讨论.
他定义了Car类:
public class Car {
public void drive() {
System.out.println("Going down the road!");
}
}
Run Code Online (Sandbox Code Playgroud)
然后他继续说:
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.
}
}
Run Code Online (Sandbox Code Playgroud)
我只是想知道当JoyRide不是Car的扩展时我们如何从类Car调用drive().是因为方法whatsInTheGarage()是返回类型Car,因此它"以某种方式"继承了该类?
谢谢.
想想这段代码:
whatsInTheGarage().drive();
Run Code Online (Sandbox Code Playgroud)
作为一个简写:
Car returnedCar = whatsInTheGarage();
returnedCar.drive();
Run Code Online (Sandbox Code Playgroud)
现在清楚了吗?所有类似C具有类c语法的语言表现得像这样.
更新:
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
Run Code Online (Sandbox Code Playgroud)