I got stuck with the following line of code:
getLogger().info("Text Goes Here"); // This command outputs the text to console
I understand the basics on how objects work and are called, but in the videos that I watched on youtube, vivz (the author), never explained about calling methods inside methods (at least that's what I think is happening in the above code).
He explained about
ClassName.variable
xVariable.method()
but nothing related to
someMethod().anotherMethod();
in beginners terms, could anyone explain the concept or some explanation on what is going on here?
Basically, I want to know if info()
is a method inside getLogger()
, or what is getLogger()
and info()
in this case?
This is called Method Chaining.
Method chaining is a common syntax for
invoking multiple method calls
in object-oriented programming languages. Each method returns an object, allowing the calls to be chained together in a single statement without requiring variables to store the intermediate results.
It is not method inside method, these are two method calls. First getLogger()
is called and on the return value (object) next info(String)
is called. You are chaining the two method calls in a single statement.
I will give you an example to understand this using String.concat()
:
public static void main(String[] args) {
String first = "First";
// Storing the resulting instance and then call again.
String s1 = first.concat(" Second");
s1 = s1.concat(" Third.");
System.out.println(s1);
// This is method chaining using String class with concat() method.
String s2 = first.concat(" Second").concat(" Third.");
System.out.println(s2);
}
Here String.concat()
returns the instance of String
after the concatenation. Now you have the option of storing the instance in a variable and then again call the concat()
on that or using the same instance directly.