版权声明:如需转载,请注明出处 https://blog.csdn.net/baidu_41813368/article/details/84196688
this关键字的三大用途
1.this调用本类属性
在一个类中我们进行一个构造方法时,需要用到本类的属性,我们首先采用以下的构造方法.
//构造方法(创建对象)
public Car(String brand,String color,String num){
brand = brand;
color = color;
num = num;
}
在上面的代码中可以看出来,当参数与属性同名时,容易产生混淆,类中的属性就无法被正确赋值,此时我们加上this关键字便可以正确给对象属性赋值.
//构造方法(创建对象)
public Car(String brand,String color,String num){
this.brand = brand;
this.color = color;
this.num = num;
}
只要在类中方法访问类中的属性,就一定要加上this关键字
2.this调用本类的方法
this调用本类方法有两种情况
1.调用普通方法this.方法名(参数)
2.调用构造方法this(参数)
调用普通方法
//构造方法(创建对象)
public Car(String brand,String color,String num){
this.brand = brand;
this.color = color;
this.num = num;
this.run();//调用普通方法
}
//普通方法
String carInfo(){
return " 车牌: "+brand+" 颜色: "+color+" 车牌号: "+num;
}
void run(){
System.out.println("一辆车牌号为"+num+"的车在高速路上行驶");
}
//测试
public class Test1{
public static void main(String[] args){
Car car1 = new Car("宝马","黑色","1235");
System.out.println(car1.carInfo());
}
}
输出结果
虽然调用本类普通方法不需要加this也可以正常调用,但强烈建议加上,加上this的目的可以区分方法的定义来源,(在继承中有用).
调用构造方法
在同一个类中,构造方法也是可以重载的
我们在Car类中,重载以下构造方法
//构造方法(创建对象)
public Car(String color,String num){
this.color = color;
this.num = num;
}
public Car(String brand,String color,String num){
this.brand = brand;
this.color = color;
this.num = num;
}
//方法
String carInfo(){
return " 品牌: "+brand+" 颜色: "+color+" 车牌号: "+num;
}
//测试
public class Test1{
public static void main(String[] args){
Car car1 = new Car("宝马","黑色","1235");
Car car2 = new Car ("白色","1111");
System.out.println(car1.carInfo());
System.out.println(car2.carInfo());
}
}
测试结果
在上面的代码中可以看出代码有重复的部分,这时我们就可以通过this(参数)来调用构造方法,减少代码的重复
//构造方法(创建对象)
public Car(String color,String num){
this.color = color;
this.num = num;
}
public Car(String brand,String color,String num){
this(brand,color);//调用本类有参的构造方法
this.num = num;
}
//方法
String carInfo(){
return " 品牌: "+brand+" 颜色: "+color+" 车牌号: "+num;
}
//测试
public class Test1{
public static void main(String[] args){
Car car1 = new Car("宝马","黑色","1235");
Car car2 = new Car ("白色","1111");
System.out.println(car1.carInfo());
System.out.println(car2.carInfo());
}
}
测试结果
我们可以看出输出结果还是一样的
注意:
1.构造方法中通过this调用本类的构造方法要放到构造方法的第一行代码
2.使用this调用构造方法时,请留有出口
3.this表示当前对象
为了验证this表示当前对象,我们加入以下代码
//方法
String carInfo(){
System.out.println(this);//打印当前对象this的标识符
return " 品牌: "+brand+" 颜色: "+color+" 车牌号: "+num;
}
//测试
public class Test1{
public static void main(String[] args){
Car car1 = new Car("宝马","黑色","1235");
Car car2 = new Car ("白色","1111");
System.out.println(car1);//打印当前car1的标识符
System.out.println(car1.carInfo());
System.out.println(car2);//打印当前car2的标识符
System.out.println(car2.carInfo());
}
}
测试结果
我们可以看出,this和car的标识符是一样的,所以this表示当前对象
只要对象调用了本类中的方法,这个this就表示当前执行的对象(调用当前方法的对象)