黑马程序员技术交流社区

标题: this关键字 [打印本页]

作者: 史世锋    时间: 2015-9-10 21:25
标题: this关键字
file:///G:/JAVA/笔记/temp/d4cbabcc-99ae-440e-8319-4727de9b29db_4_files/76762787-07fc-40d7-873f-ce25abfab8c4.png[attach]86961[/attach]


哪个对象在调用函数,那么该函数内的this就代表这个对象

class Person
{
    private String name;
    Person(String name)
    {
        this.name = name;
    }
}



其实很多地方都省略了this关键字,如下图



file:///G:/JAVA/笔记/temp/d4cbabcc-99ae-440e-8319-4727de9b29db_4_files/c3f1713a-a680-4dfe-a63b-517ca9b66ce0.png



this的应用:

当定义类中函数时,该函数内部要用到调用该函数的对象时,

用this来表示这个对象

但凡本类函数内部使用了本类对象,都用this表示
class Person
{
     private int age;
     Person(int age)
     {
         this.age = age;
     }
     //比较两个人的年龄大小,这时需要用到本类对象
     public boolean compare(Person p)
     {
          return this.age == p.age;
     }
}




this关键字在构造函数中的应用

class Person
{
    private String name;
    private int age;
    Person(String name)
    {
       this.name = name;
    }
    Person(String name, int age)
    {
//      this.name = name;  //给name初始化在上面的构造函数中已经存在了,我们可以直接用
//      Person(name); //这样是错误的
        this(name);   //这样写,可以称为this语句,只可以放在构造函数的第一行
        this.age = age;
    }
}


file:///G:/JAVA/笔记/temp/d4cbabcc-99ae-440e-8319-4727de9b29db_4_files/ad76a18b-bfd3-41ba-a2b3-4d64be8f4b60.png


















作者: 史世锋    时间: 2015-9-10 21:26
图片怎么显示不出来呢




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2