java中this的用法
this是java中的关键字,主要有三种用法:
this.属性
这里举一个简单的三个数相加的列子
class Add{
public int x;
public int y;
public int z;
public Add(int x,int y,int z){
x = x;
y = y;
z = z;
}
public void print(){
System.out.println(x + y + z);
}
}
public class Test {
public static void main(String[] args) {
Add a1 = new Add(10,20,30);
a1.print();
}
}
为什么输出的结果会是0呢?
大家看这个代码块
public Add(int x,int y,int z){
x = x;
y = y;
z = z;
}
形参和变量的名字都相同怎么能分的清谁给谁赋值呢?
此时就可以用到this
public Add(int x,int y,int z){
this.x = x;
this.y = y;
this.z = z;
}
this.代表当前对象引用,谁调用了x y z ,this就代表谁
this.方法
this可以在成员方法中调用另外一个方法
此时,我们在带三个参数的构造方法中this.print(),即调用了Add{}类中的print()方法,此时我们在new的时候,就是进行对像的实例化的时候,在执行构造方法的时候就调用了print()方法
this()//调用构造方法
this()语句必须放在方法里面的第一句
this可以实现构造方法的调用
比如在不带参数的构造方法中调用带三个参数的构造方法
可以看到,我在实例化对象的时候并没有传参数,实例化的时候调用的是不带参数的构造方法。
但是我在不带参数的构造方法中用this()给了三个参数,这时候就调用了带三个参数的构造方法。
注意:构造方法中不能用this来自己调用自己
不能用this形成闭环。
例如:在不带参数的构造方法中调用带三个参数的构造方法,又在带三个的构造方法中调用不带参数的构造方法