1.普通调用与链式调用区别
普通调用
User user = new User();
user.setName("Alice");
user.setAge(25);
链式调用
User user = new User() //只执行后面的new User(),然后返回this
.setName("Alice") //this调用该方法后继续返回this
.setAge(25); //this调用该方法后才把this赋值给第一行的user变量
2.如何实现链式调用
(1)先自定义链式调用(实现一个 User
类)
注意:set方法与之前的不一样,否则后面不能使用链式调用
public class User {
private String name;
private int age;
// 链式方法:setName 返回 this
public User setName(String name) {
this.name = name;
return this; // 返回当前对象
}
// 链式方法:setAge 返回 this
public User setAge(int age) {
this.age = age;
return this; // 返回当前对象
}
}
// 使用链式调用创建 User 对象
User user = new User()
.setName("Alice")
.setAge(25);
(2).执行链式调用
User user = new User() //只执行后面的new User(),然后返回this
.setName("Alice") //this调用该方法后继续返回this
.setAge(25); //this调用该方法后才把this赋值给第一行的user变量
3.实现链式调用的关键
方法返回 this
每个方法执行后返回当前对象(不再是void):
public User setName(String name) {
this.name = name;
return this; // 核心!
}