this关键字的用法

来源:互联网 发布:java项目当当网源代码 编辑:程序博客网 时间:2024/05/10 05:35
1.表示类中的属性(为了明确表示是类中的属性)
class Person{private String name;private int age;public Person(String name, int age){this.name = name;//表示当前对象的name属性this.age = age;//表示当前对象的age属性}};
2.使用this关键字调用构造方法
如果在一个类中有多个构造方法的话,可以利用this关键字相互调用。注意:
(1)this()调用构造方法的语句只能放在构造方法的首行。、
(2)在使用this()调用本类中的其他构造方法的时候,至少有一个构造方法是不用this调用的。
class Person{private String name;private int age;public Person(){//此构造方法中不能调用this("Tom",34)。构造方法递归调用无限循环System.out.println("The same is");}public Person(String name){this();//调用无参数的构造方法this.name = name;}public Person(String name, int age){this(name);//调用有参数的构造方法this.age = age;}public void printInfo(){System.out.println("name = " + this.name + ", age = " + this.age);}};
3.使用this表示当前对象。(例如:比较两个对象是否相等,只要姓名和年龄相同就表示两个对象相等)
class Person{private String name;private int age;public Person(String name,int age){this.setName(name);this.setAge(age);}public boolean compare(Person per){//判断两个对象是否相等if(per == this){//判断是不是本身调用本身return true;}//只要name和age相同,则两个对象就相等if(per.getName().equals(this.getName()) && per.getAge() == this.getAge()){return true;}else{return false;}}public void setName(String name){this.name = name;}public void setAge(int age){this.age = age;}public String getName(){return this.name;}public int getAge(){return this.age;}};public class ThisDemo03{public static void main(String args[]){Person per1 = new Person("Tom",34);Person per2 = new Person("Tom",35);if(per1.compare(per2)){System.out.println("The same is");}else{System.out.println("The same is not");}}}; 
总结:以上this关键字的三个用法,归根结底是this表示当前对象。
0 0
原创粉丝点击