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

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.

1 answer

  • answered 2020-02-12 23:04 Carcigenicate

    chewingGums returns an object that has a quantity method.


    Would be the same as

    Gum gum = chewingGums();

    Where Gum is the type that chewingGums returns.

    It's similar to this line:

    new Scanner().nextInt();

    new Scanner() evaluates to a Scanner object, then nextInt is called on that object. This isn't a great example since Scanner is a constructor, but it's the simplest method chaining example I could think of.