System.out.println - Is this method chaining in Java?
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 开发者_StackOverflowthis 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.
out
is not a method - it is an instance of PrintStream
, of which println
is a method.
See http://java.sun.com/j2se/1.5.0/docs/api/java/lang/System.html#out
精彩评论