问题描述:

I know some basics of java language.

But I don't know some statements like this:

method1().method2().method3()

Two or three methods separated whit dots operator! I cannot understand it.

What does it mean? How can I use them? Do they process from left to right or reverse?

Does they return special values or not?

How can I understand I should some methods separate whit dot?

How can I create methods like this?

网友答案:

I will gave you a little example.

method1().method2().method3();

getYear().toString().trim();

first execute get year() which returns a Integer:

1995.toString().trim();

secound execute toString() method of integer class which returns an string:

"1995".trim();

at least the compiler would execute trim() method of string class.

the first method return a number then you use toString() method on this number and format it to a string. this will return a string and then you can use the trim() method of string class to trim() the string. you are executed the next method after you get the return from the method in front of.

网友答案:

That is chaining of method calls. THe object returned by method1() will call method2() As an example,

public static String methodToReturnString() {
    return "someString";
}

You call this using String subString = methodToReturnString().toLowerCase().substring(3); This returns a String estring.

This is similar to the code as follows.

String s1 = methodToReturnString();
String s2 = s1.toLowerCase();
String s3 = s2.substring(3);
System.out.println(s3);

As for generating this s3 variable, we needed to store the return values of method in some variables which is not needed. Using method chaining, we have avoided variables s1, s2 here.

网友答案:

method1 returns object, which has method2 and then you can call method2, which returns object that has method3 and you call it.

网友答案:

Your statement will be interpreted as follows:

  1. Invoke method1(). The return value will be some object.
  2. Invoke method2() on the object returned by method1(). This method too must have a return value.
  3. Invoke method3() on the object returned by method2().

You can rewrite this as:

SomeType value1 = method1();
SomeOtherType value2 = value1.method2();
value2.method3();
网友答案:

See... For example we might have

String s= "abcde";
String str =  s.trim().subString(2); 

1 --> trim() is called on "s".
2 --> subString() is called on the result of s.trim() 
网友答案:

Method1 returns object1, which has method2 which returns object2, which has method3.

Object1 and object2 and current object can be identical, which is used in builder pattern.

Something like:

Student {
    Semester lastFinishedSemester();
}

Semester {
    Courses registeredCourses();
}

Courses {
    void printCoursesAndGrades();
}

now if you are in one of student methods, you can call:

lastFinishedSemester().registeredCourses().printCoursesAndGrades();
相关阅读:
Top