一、表示类中属性
class Person{ // 定义Person类
private String name ; // 姓名
private int age ; // 年龄
public Person(String name,int age){ // 通过构造方法赋值
this.name = name ; // 为类中的name属性赋值
this.age = age ;// 为类中的age属性赋值
}
public String getInfo(){ // 取得信息的方法
return "姓名:" + name + ",年龄:" + age ;
}
};
public class ThisDemo02{
public static void main(String args[]){
Person per1 = new Person("张三",33) ; // 调用构造实例化对象
System.out.println(per1.getInfo()) ; // 取得信息
}
};
运行结果:
姓名:张三,年龄:33
二、调用构造方法
package methoud;
class Person{ // 定义Person类
private String name ; // 姓名
private int age ; // 年龄
public Person(){ // 无参构造
System.out.println("新对象实例化") ;
}
public Person(String name){
this() ;// 调用本类中的无参构造方法
this.name = name ;
}
public Person(String name,int age){ // 通过构造方法赋值
this(name) ;// 调用有一个参数的构造方法
this.age = age ;// 为类中的age属性赋值
}
public String getInfo(){ // 取得信息的方法
return "姓名:" + name + ",年龄:" + age ;
}
};
public class ThisDemo06{
public static void main(String args[]){
Person per1 = new Person("张三",33) ; // 调用构造实例化对象
System.out.println(per1.getInfo()) ; // 取得信息
}
};
运行结果:
新对象实例化
姓名:张三,年龄:33
注意:
1、this()调用其他构造方法的语句只能放在构造方法(在其他普通方法里是不行的)的首行;
2、在使用this调用其他构造方法的时候,至少有一个构造方法是不用this调用的。(必须要有结尾,不能无限期的调用下去,循环递归调用);
三、调用当前对象
class Person{ // 定义Person类
public String getInfo(){ // 取得信息的方法
System.out.println("Person类 --> " + this) ; // 直接打印this
return null ; // 为了保证语法正确,返回null
}
};
public class ThisDemo06{
public static void main(String args[]){
Person per1 = new Person() ; // 调用构造实例化对象
Person per2 = new Person() ; // 调用构造实例化对象
System.out.println("MAIN方法 --> " + per1) ; // 直接打印对象
per1.getInfo() ; // 当前调用getInfo()方法的对象是per1
System.out.println("MAIN方法 --> " + per2) ; // 直接打印对象
per2.getInfo() ; // 当前调用getInfo()方法的对象是per2
}
};
运行结果:
MAIN方法 --> methoud.Person@2a139a55
Person类 --> methoud.Person@2a139a55
MAIN方法 --> methoud.Person@15db9742
Person类 --> methoud.Person@15db9742
可见,用this调用的是当前对象,与直接per1,per2是一样的效果。