加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

Java隐式方法/参数?

发布时间:2020-12-15 05:08:12 所属栏目:Java 来源:网络整理
导读:我正在阅读一本关于 Android编程的书,在开头章节中有一篇关于Java的小参考指南.但是,我对一些我不太了解的隐式参数进行了讨论. 他定义了Car类: public class Car { public void drive() { System.out.println("Going down the road!"); }} 然后他继续说: p
我正在阅读一本关于 Android编程的书,在开头章节中有一篇关于Java的小参考指南.但是,我对一些我不太了解的隐式参数进行了讨论.

他定义了Car类:

public class Car {
  public void drive() {
    System.out.println("Going down the road!");
  }
}

然后他继续说:

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.
 }
}

我只是想知道当JoyRide不是Car的扩展时我们如何从类Car调用drive().是因为方法whatsInTheGarage()是返回类型Car,因此它“以某种方式”继承了该类?

谢谢.

解决方法

想想这段代码:

whatsInTheGarage().drive();

作为一个简写:

Car returnedCar = whatsInTheGarage();
returnedCar.drive();

现在清楚了吗?具有类似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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读