简体   繁体   English

方法调用作为Java中另一个方法的参数

[英]Method call as a parameter of another method in Java

so i am required to do an assignment in which i follow JUnit test file to create all the code that i need(almost like a design doc), basicly its coding a vending machine, inside the test file there is this code right here所以我需要做一个作业,我按照 JUnit 测试文件来创建我需要的所有代码(几乎就像一个设计文档),基本上它编码一个自动售货机,在测试文件中有这个代码就在这里

assertThat(snackMachine.chewingGums().quantity()).isEqualTo(DEFAULT_QUANTITY - 1);
assertThat(snackMachine.chips().quantity()).isEqualTo(DEFAULT_QUANTITY - 1);
assertThat(snackMachine.chocolates().quantity()).isEqualTo(DEFAULT_QUANTITY - 1);

and i was scratching my head, looking at this, how can a method inside a class have a method inside it aswell, so chewingGums() has quantity() inside of it????, is this possible in java?, because i have looked all over, and i havent seen a way to implement it, like it shows here.我正在挠头,看着这个,一个类中的方法怎么能在它里面也有一个方法,所以chewingGums()里面有quantity()????,这在java中可能吗?,因为我已经看遍了,我还没有看到实现它的方法,就像这里显示的那样。

chewingGums returns an object that has a quantity method. chewingGums返回一个具有quantity方法的对象。

chewingGums().quantity()

Would be the same as将与

Gum gum = chewingGums();
gum.quantity();

Where Gum is the type that chewingGums returns.其中GumchewingGums返回的类型。

It's similar to this line:它类似于这一行:

new Scanner().nextInt();

new Scanner() evaluates to a Scanner object, then nextInt is called on that object. new Scanner()计算结果为Scanner对象,然后在该对象上调用nextInt This isn't a great example since Scanner is a constructor, but it's the simplest method chaining example I could think of.这不是一个很好的例子,因为Scanner是一个构造函数,但它是我能想到的最简单的方法链示例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM