this关键字
this核心概念指代当前对象,利用this关键字可以实现类属性调用,类方法调用,以及表示当前对象
this调用属性
实例代码:如下,我构造方法出入String n 和double p分别赋值car的name属性和car的price属性,这个时没有啥问题的。
class Car{
private String name;
private double price;
public Car(String n, double p){
name = n;
price = p;
}
public String getCarInfo(){
return "车品牌:"+name+", 价格:"+price;
}
}
public class TestThis{
public static void main(String[] arg){
Car car = new Car("兰博基尼", 5500000);
System.out.println(car.getCarInfo());//结果:车品牌:兰博基尼, 价格:5500000.0
}
}
实例代码:如下,当我吧构造方法的参数名称换成String name和double price时,结果是车品牌:null, 价格:0.0,这是为什么呢?主要是作用域问题,java以{}大括号为作用域,当他发现传入的参数为name和price时,这个时候赋值的操作也是name和price,那么他就不会再去类的属性里面查找对应的name和price(就近原则),这就导致car的属性name和price没有被赋值,打印出来的就是对应属性类型的默认值。
class Car{
private String name;
private double price;
public Car(String name, double price){
name = name;
price = price;
}
public String getCarInfo(){
return "车品牌:"+name+", 价格:"+price;
}
}
public class TestThis{
public static void main(String[] arg){
Car car = new Car("兰博基尼", 5500000);
System.out.println(car.getCarInfo());//车品牌:null, 价格:0.0
}
}
通过上面代码,这个时候this的作用就体现出来了,代码如下:
class Car{
private String name;
private double price;
public Car(String name, double price){
this.name = name;
this.price = price;
}
public String getCarInfo(){
return "车品牌:"+this.name+", 价格:"+this.price;
}
}
public class TestThis{
public static void main(String[] arg){
Car car = new Car("兰博基尼", 5500000);
System.out.println(car.getCarInfo());//结果:车品牌:兰博基尼, 价格:5500000.0
}
}