this
this可以看成是自身的一个引用,和python中的self有一些相似
用法1,区分成员名字
public class Example {
private final int arg1;
private final int arg2;
public Example(int arg1, int arg2) {
this.arg1 = arg1;
this.arg2 = arg2;
}
public void method1() {
System.out.println("This's method1");
}
public void method2() {
this.method1();
System.out.println("This's method2");
}
...
}
用法二自身引用,这里举一个线程锁的例子
public class MyThread implements Runnable {
...
public void myMethod() {
...
synchronized(this) {
...
}
...
}
...
}
3 构造时重载其他Creater
public class Example {
private final String name;
private final int arg1;
private final int arg2;
public Example(String name, int arg1) {
this.name = name;
this.arg1 = arg1;
}
public Example(int arg2) {
this("nothing", 100); //这一句必须时第一行
this.arg2 = arg2;
}
...
}
Over!