1.this关键字的定义:
    image.png
    this关键字的作用:
    如果不用this关键字的话:在name = name时,他是赋值给形参(就近赋值),这个时候加上this关键字,idea就知道你是赋值给当前对象的name
    image.png
    this出现在成员方法中的用法:
    image.png

    1. package com.itheima.thisdemo;
    2. /*
    3. 目标:理解this
    4. this表示当前对象的地址
    5. */
    6. public class Test {
    7. public static void main(String[] args) {
    8. //创建汽车对象(先有类,然后有对象--new出来)
    9. Car c = new Car();// com.itheima.thisdemo.Car@404b9385
    10. c.run();// com.itheima.thisdemo.Car@404b9385
    11. // 输出对象的地址com.itheima.thisdemo.Car@404b9385
    12. System.out.println(c);
    13. System.out.println("----------------");
    14. Car c1 = new Car("奔驰",18.8);
    15. System.out.println(c1.name);
    16. System.out.println(c1.price);
    17. c1.gowith("宝马");
    18. }
    19. }
    20. // 这是一个新的的Car类
    21. package com.itheima.thisdemo;
    22. public class Car {
    23. String name;
    24. double price;
    25. /*
    26. 无参构造器
    27. */
    28. public Car(){
    29. System.out.println("无参数构造器中的this:" + this);
    30. }
    31. /*
    32. 有参构造器
    33. */
    34. // public Car(String n,double p) 像这种定义形参会被嫌弃(要做到见面知意)
    35. public Car(String name,double price){
    36. // 不写this会被赋值给形参(就近赋值)
    37. this.name = name;
    38. this.price = price; // 用this关键字可以让idea知道左边的price是当前对象成员的price
    39. }
    40. // this在对象方法的用法
    41. public void gowith(String name){
    42. // System.out.println(name + "正在和" + name + "一起比赛"); // 如果不写this都会输出传入值得name
    43. System.out.println(this.name + "正在和" + name + "一起比赛");
    44. }
    45. public void run(){
    46. System.out.println("方法中的this:" + this);
    47. }
    48. }