this关键字

this核心概念指代当前对象,利用this关键字可以实现类属性调用,类方法调用,以及表示当前对象

this调用属性

实例代码:如下,我构造方法出入String n 和double p分别赋值car的name属性和car的price属性,这个时没有啥问题的。

  1. class Car{
  2. private String name;
  3. private double price;
  4. public Car(String n, double p){
  5. name = n;
  6. price = p;
  7. }
  8. public String getCarInfo(){
  9. return "车品牌:"+name+", 价格:"+price;
  10. }
  11. }
  12. public class TestThis{
  13. public static void main(String[] arg){
  14. Car car = new Car("兰博基尼", 5500000);
  15. System.out.println(car.getCarInfo());//结果:车品牌:兰博基尼, 价格:5500000.0
  16. }
  17. }

实例代码:如下,当我吧构造方法的参数名称换成String name和double price时,结果是车品牌:null, 价格:0.0,这是为什么呢?主要是作用域问题,java以{}大括号为作用域,当他发现传入的参数为name和price时,这个时候赋值的操作也是name和price,那么他就不会再去类的属性里面查找对应的name和price(就近原则),这就导致car的属性name和price没有被赋值,打印出来的就是对应属性类型的默认值。

  1. class Car{
  2. private String name;
  3. private double price;
  4. public Car(String name, double price){
  5. name = name;
  6. price = price;
  7. }
  8. public String getCarInfo(){
  9. return "车品牌:"+name+", 价格:"+price;
  10. }
  11. }
  12. public class TestThis{
  13. public static void main(String[] arg){
  14. Car car = new Car("兰博基尼", 5500000);
  15. System.out.println(car.getCarInfo());//车品牌:null, 价格:0.0
  16. }
  17. }

通过上面代码,这个时候this的作用就体现出来了,代码如下:

  1. class Car{
  2. private String name;
  3. private double price;
  4. public Car(String name, double price){
  5. this.name = name;
  6. this.price = price;
  7. }
  8. public String getCarInfo(){
  9. return "车品牌:"+this.name+", 价格:"+this.price;
  10. }
  11. }
  12. public class TestThis{
  13. public static void main(String[] arg){
  14. Car car = new Car("兰博基尼", 5500000);
  15. System.out.println(car.getCarInfo());//结果:车品牌:兰博基尼, 价格:5500000.0
  16. }
  17. }