对自己的一个引用
1.为了和参数区别用this
void setXX(int xx){
this.xx=xx;
}
2.构造函数,调用构造函数
public XX(){
this(null,null);
}
3.其他就是和一般引用一样了,不过不可以改this,是个只读的.
1.为了和参数区别用this
void setXX(int xx){
this.xx=xx;
}
2.构造函数,调用构造函数
public XX(){
this(null,null);
}
3.其他就是和一般引用一样了,不过不可以改this,是个只读的.
private int i = 0;
Leaf increment() {
i++;
return this;
}
void print() {
System.out.println("i = " + i);
}
public static void main(String[] args) {
Leaf x = new Leaf();
x.increment().increment().increment().print();
}
} ///:~
简单的说,this能够让你得到当前对象的引用(reference)。上面的:x.increment().increment().increment().print()就是这样。increment()中的this就得到了x。
java中有必用this的三种情况。I.数据成员和形参重命
class Bird{
int num;
void feather(int num) {
this.num = num
}
}
this.num表明所取用的是数据成员numII.返回目前的对象
需要在return语句中写:return this;
public class Leaf {
private int i = 0;
Leaf increment() {
i++;
return this;
}
void print() {
System.out.println("i = " + i);
}
public static void main(String[] args) {
Leaf x = new Leaf();
x.increment().increment().increment().print();
}
}III.在构造函数中调用构造函数(C++不允许如此)
class Bird{
Bird(int i) {
System.out.println(“Bird(int i)”);}
Bird() {
this(1);
System.out.println(“Bird(int i)”); }
public static void main(String[] args){
Bird x = new Bird();
}
}
子类调用时用this
2。构造函数时使用