1.使用this调用本类中的属性
package com.yxf.stringdemos;
public class StringDemos {
public static void main(String[] args) {
// TODO Auto-generated method stub
Person p1 = new Person("xifeng.yang","30");
p1.getInfo();
}
}
class Person{
String name;
String age;
public Person(String name, String age){
System.out.println("Constrctor, name = " + name + ",age = " + age);
name = name;//这里不加this时,则调用构造方法赋值失败
age = age;
}
public void getInfo(){
System.out.println("name = " + name + ", age = " + age);
}
}
结果:
Constrctor, name = xifeng.yang,age = 30
name = null, age = null
2.使用this调用构造方法
如果一个类中有多个构造方法,则可以使用this关键字相互调用。
package com.yxf.stringdemos;
public class StringDemos {
public static void main(String[] args) {
// TODO Auto-generated method stub
Person p1 = new Person("xifeng.yang","30");
Person p2 = new Person("Chris Yang");
Person p3 = new Person();
p1.getInfo();
}
}
class Person{
String name;
String age;
public Person(String name, String age){
System.out.println("Person,constructor()");
this.name = name;
this.age = age;
}
public Person(String name){
this(name,null);
}
public Person(){
this(null,null);
}
public void getInfo(){
System.out.println("name = " + name + ", age = " + age);
}
}
}
这里面p1,p2,p3都会调用第一个构造方法。
3.this表示当前对象
使用this可以表示当前正在调用类的方法的对象
package com.yxf.stringdemos;
public class StringDemos {
public static void main(String[] args) {
// TODO Auto-generated method stub
Person p1 = new Person("xifeng.yang","30");
System.out.println("Main: " + p1);
p1.getInfo();
Person p2 = new Person("Chris Yang");
System.out.println("Main: " + p2);
p2.getInfo();
}
}
class Person{
String name;
String age;
public Person(String name, String age){
this.name = name;
this.age = age;
}
public Person(String name){
this(name,null);
}
public Person(){
this(null,null);
}
public void getInfo(){
System.out.println("getInfo(): " + this);
}
}
结果:
Main: com.yxf.stringdemos.Person@1fb8ee3
getInfo(): com.yxf.stringdemos.Person@1fb8ee3
Main: com.yxf.stringdemos.Person@61de33
getInfo(): com.yxf.stringdemos.Person@61de33