1.表示类中的属性(为了明确表示是类中的属性)2.使用this关键字调用构造方法class Person{ private String name; private int age; public Person(String name, int age){ this.name = name;//表示当前对象的name属性 this.age = age;//表示当前对象的age属性 } };
如果在一个类中有多个构造方法的话,可以利用this关键字相互调用。注意:
(1)this()调用构造方法的语句只能放在构造方法的首行。、
(2)在使用this()调用本类中的其他构造方法的时候,至少有一个构造方法是不用this调用的。3.使用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); } };
总结:以上this关键字的三个用法,归根结底是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关键字的用法
最新推荐文章于 2021-11-01 19:36:35 发布