Listen to the chain programming to hear strange, but write out feel actually very familiar with
1 Packagetest;2 3 Public classTest {4 String name;5 String phone;6 String Mail;7 String sex;8 PublicTest setName (String name) {9 This. Name =name;Ten return This; One } A PublicTest Setphone (String phone) { - This. Phone =phone; - return This; the } - PublicTest Setmail (String mail) { - This. Mail =Mail; - return This; + } - Public voidsetsex (String sex) { + This. Sex =sex; A } at Public Static voidMain (string[] args) { -Test test =NewTest (); -Test.setname ("Test"). Setphone ("" "). Setmail (" [email protected] "). Setsex (" neutral "); - } -}
The remaining set methods must return an object or object reference that supports the method invocation, except that the last method does not require that the object or object reference be returned, otherwise the chained call cannot be completed and a syntax error is generated.
The principle of a chained invocation is obvious: Because the first method call returns the object reference of the method, the reference can generate the next method call;
Because the last method call means the end of the call chain, there is no need to have a return type
If a method chain call is applied in an output or assignment statement, its last method usually returns an operation result.
Note improper use of the method chaining calls will weaken the readability of the program
Chained programming in Java