this的应用

来源:互联网 发布:unity3d 内嵌网页 编辑:程序博客网 时间:2024/06/07 06:15
//给人定义一个功能,用来判断是否是同龄人;class Person{private int age;private String name;Person(int age){         this.age=age;}public boolean compare(Person p){return this.age==p.age;//!!!}}class PersonDemo3{public static void main(String[] args){Person  p=new Person(20);Person  p1=new Person(25);boolean b=p.compare(p1);//!!!System.out.println(b);}}

this的应用:当定义类中函数时,该函数内部要用到调用该函数的对象时,这时用this来表示这个对象。
                      但凡本类功能内部使用了本类对象,都用this表示

 

 this语句:构造函数之间调用

注意:只能定义在构造函数的第一行;因为初始化要先执行

class Person{private int age;private String name;Person(int name){         this.name=name;}Person(String name,int age){this(name);//调用上面构造函数;相当于p(name);//this.name=name;         this.age=age;}}class PersonDemo3{public static void main(String[] args){Person  p=new Person("lisi",20);}}


 

 

 

 

0 0