I am wondering about the the following piece of Java code:
"System.out.println". I am right about this:
"System" is a static class. ".out" is a method of class "System". This is the bit I am slighty confused about ".println"-- what class / object is this a method of?
Also, is this concept known as "method chaining"?
Thanks
GF
No, it's not method chaining. You're right about System being a class (just a regular class, not "static" - only inner classes can be static), but out is a static field of the class (of the type java.io.PrintStream), and only println() is a method of PrintStream.
This is an example of method chaining:
String s = "Long String ".toUpperCase().substring(4).trim()
The class System has a member variable 'out', of type PrintStream. It's not a method.
Class PrintStream has a method println(String).
So no, not method chaining.
Method chaining, as far as I know, is just returning this where you might return void, allowing for multiple invocations of methods in a single statement and perhaps a more natural expression of a DSL. You can see it in action in the StringBuilder's append(String) method
StringBuilder builder = new StringBuilder()
.append("I am a ")
.append("String")
.append("Builder");
If you're interested in knowing more, Martin Fowler talked about Method Chaining here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With