0、第一种用途:this指向当前对象的引用
this指向调用当前方法的对象。
public class Age {
// 年龄
int number = 10;
// 生日
Age birthday() {
sing(); // 等同于 this.sing();
number++; // 等同于 this.number++;
return this;
}
// 唱生日歌
void sing() {
System.out.println("祝你生日快乐...");
}
public static void main(String[] args) {
Age age = new Age();
age.birthday().birthday().birthday();
System.out.println("目前年龄为:" + age.number);// 结果为:13
}
}
在方法中调用当前类其它字段或方法需要用到
this,如this.sing(),为了方便,编译器允许将this省略。
birthday()方法返回this,表明返回当前对象。所以可以连续调用age.birthday().birthday().birthday()。
记住:static方法里没有this,由于this指向当前调用的对象,而static方法(静态方法)不属于任何对象,只属于类。
1、第二种用途:this调用构造方法
在构造方法中,this后面跟参数可以调用另一个构造方法,编译器会根据参数列表自动匹配到相应的构造方法。如this(name, age);
public class Student {
// 姓名
String name;
// 年龄
int age;
// 性别
String sex;
public Student(String name) {
this.name = name;
}
public Student(String name, int age) {
this(name);
this.age = age;
}
public Student(String name, int age, String sex) {
this(name, age);
this.sex = sex;
}
}
2、Builder模式(构造者模式)
Builder模式也叫构造者模型,顾名思义就是通过多个参数构造出一个新的对象。Builder模式超级常见,在日后的开发中常常会使用到Builder模式的类库。
Builder模式常常用于类字段超级多,而且参数往往不是必须的情况下。(这里为了方便阅读就只有三个参数)。
public class Student {
String name;
int age;
String sex;
private Student(Builder builder) {
this.name = builder.name;
this.age = builder.age;
this.sex = builder.sex;
}
public static class Builder {
String name;
int age;
String sex;
// name是必须的
public Builder(String name) {
this.name = name;
}
public Builder age(int age) {
this.age = age;
return this;
}
public Builder sex(String sex) {
this.sex = sex;
return this;
}
public Student build() {
return new Student(this);
}
}
public static void main(String[] args) {
// 创建构造者
Student.Builder builder = new Student.Builder("张三")
.age(18)
.sex("女");
// 构造者创建目标对象
Student s1 = builder.build();
// 简约写法
Student s2 = new Student.Builder("张三")
.age(18)
.sex("女")
.build();
}
}
这里
Student类里面有个内部类Builder,也叫做嵌套类(static修饰的内部类叫做嵌套类)。
内部类
Builder和外部类Student持有一样的字段。
外部类
Student的构造方法是private修饰的,在其它类里面无法直接通过new创建Student对象。构造方法参数接收的是内部类对象引用:private Student(Builder builder)
Builder内部类的age(int age)、sex(String sex)方法都返回this(Builder对象引用)。
内部类
Builder通过build()方法里new Student(this)创建外部类Student对象。
嵌套类就是构造者,通过它来创建Student对象。如下:
// 创建构造者
Student.Builder builder = new Student.Builder("张三")
.age(18)
.sex("女");
// 构造者创建目标对象
Student s1 = builder.build();
// 简约写法
Student s2 = new Student.Builder("张三")
.age(18)
.sex("女")
.build();
创建普通类:new XxxClass(); 创建嵌套类:new OutClass.InnerClass()
3、结语
关注微信公众号:小虎哥的技术博客