java中this关键字的使用总结

一、this关键字的定义

Java中为解决变量的命名冲突和不确定性问题,引入关键字this代表其所在方
法的当前对象的引用:

  • Java虚拟机会给每个对象分配this,代表当前对象
  • 那个对象调用,this就代表那个对象
  • this关键字可访问本类的属性、方法、构造器
  • this可以用来区分当前类的属性和局部变量
  • 访问构造器语法:this(参数列表),必须放在首位;只能在构造器中使用,只能在构造器中调用另外一个构造器
  • this不能在类定义的外部使用,只能在类定义的方法中使用。

二、this关键字用法总结

  1. this.property 访问属性
  2. this.method() 访问方法
  3. this(); 调用本类中其他构造方法

三、举例说明this关键字的用法

1.this.property。举例说明带this关键字和不带this关键字的区别

不加this出现的情况:

public class ThisMethod {    public static void main(String[] args) {        MyDate myDate = new MyDate();        myDate.setDate(2020,9);        myDate.PrintDate();    }}class MyDate {    public int year;    public int month;    public void setDate(int year, int month) {        year = year;//这里没有加this        month = month;//这里没有加this    }    public void PrintDate() {        System.out.println(year + "年 " + month + "月 ");    }}

我们想要达到的预期结果是2020年9月。

而实际运行结果如下:

加上this之后才能达到我们的预期

public class ThisMethod {    public static void main(String[] args) {        MyDate myDate = new MyDate();        myDate.setDate(2020,9);        myDate.PrintDate();    }}class MyDate {    public int year;    public int month;    public void setDate(int year, int month) {        this.year = year;//这里没有加this        this.month = month;//这里没有加this    }    public void PrintDate() {        System.out.println(year + "年 " + month + "月 ");    }}

达到我们的预期:


2.this.method()举例说明

public class ThisMethod02 {    public static void main(String[] args) {        Student student = new Student();        student.name = "小小明";        student.doClass();    }}class Student {    public String name;    public void doClass() {        System.out.println(name + "上课");        this.doHomeWork();    }    public void doHomeWork() {        System.out.println(name + "正在写作业");    }}

输出结果:


(3)this() 调用本类中其他构造方法

要注意以下几点:

  • 访问构造器语法:this(参数列表),必须放在首位;只能在构造器中使用,只能在构造器中调用另外一个构造器
  • this不能在类定义的外部使用,只能在类定义的方法中使用。
public class ThisMethod03 {    public static void main(String[] args) {        Student01 student01 = new Student01();        student01.showMessage();    }}class Student01{    public  String name;    public  int  age;    //无参构造方法    public Student01() {        //小李解读:        //1.this 放在首位        //2.只能在构造器中使用        //3.只能在构造器中调用另外一个构造器        //调用带有两个参数的构造器        this("张三",20);        System.out.println("这是无参的构造器");    }    public Student01(String name, int age) {        this.name = name;        this.age = age;        System.out.println("这是带有两个参数的构造器");    }    public void showMessage(){        System.out.println("姓名:"+name+",年龄:"+age);    }}

输出结果:


发表评论
留言与评论(共有 0 条评论) “”
   
验证码:

相关文章

推荐文章