Hi all,
I am curious about this portion of the code:
public class Solution {
public static void main(String[] args) {
getDeliciousDrink().taste();
System.out.println(getWine().getCelebrationName());
System.out.println(getBubblyWine().getCelebrationName());
System.out.println(getWine().getCelebrationName());
The method getDeliciousDrink() is followed by a call to another method .taste().
1) First am I understanding this correctly? Is a method calling another method?
2) Why wouldn't we want to simply call the desired method? Why the run-around?
Thanks!
Calling a method on a method?
Archived
Comments (5)
- Popular
- New
- Old
You must be signed in to leave a comment
ImDevin
10 June 2021, 02:57
Wine "Is-A" Drink (Wine extends Drink) and that's why even though Wine is returned we can use it to call the Drink's method.
0
Ryan Palmer
21 May 2021, 02:31
Thank you Jurij, that makes sense. So if I understand correctly, if a method returns an object, I can use the dot operator to immediately call another method on that to be returned object? Is there a name for this?
Thanks!
0
Thomas
21 May 2021, 07:16
In Java expressions get evaluated from left to right. That makes method chaining possible. Of course the method you call needs to return the correct type for the next method you intend to invoke ;)
As a fun fact you can read about the fluent design pattern, too.
+1
Jurij Thmsn
21 May 2021, 08:15
method chaining example
+1
Jurij Thmsn
20 May 2021, 07:32
1) the method isn't calling another method.
The getDeliciousDrink() method returns a Wine object and then you're immediately calling that object's taste() method.
look at the return type of the method:
As stated in the Conditions (7. The Solution class must implement the getDeliciousDrink() method, which returns a Wine object.) it has to be a Wine object.
To make clear what happens, look at this code:
2) You can't call the taste() method without a Drink object, because it is implemented in the Drink class
(Condition: 2. The Drink class must implement a public void taste() method that displays "Delicious".). Thats why 3. The Wine class must be in a separate file and be a descendant of the Drink class..
+1