this只能用于方法体内,并且只能在非静态方法中使用,指向对象本身
public class Test1 {
private String name;
private int age;
private String email;
public Test1(String name, int age , String em) {
this.name = name;// 成员变量和参数同名,成员变量被屏蔽,用"this.成员变量"的方式访问成员变量.
this.age = age;
email = em;
}
public Test1(){
this("jack",18,"123@123.com");// 通过this调用另一个构造方法
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setAge(int age) {
this.age = age;
}
public int getAge() {
return age;
}
public void setEmail(String email) {
this.email = email;
}
public String getEmail() {
return email;
}
public int getNum(){
int age;
age=this.age+1;//局部变量与成员变量同名,成员变量被屏蔽,用"this.成员变量"的方式访问成员变量.
return age;
}
//返回当前实例的引用
public Test1 getTest(){
return this;
}
public static void main(String args[]) {
Test1 a1 = new Test1();
System.out.println("age:"+a1.getAge()+",name:"+a1.getName()+",email:"+a1.getEmail());
System.out.println(a1.getNum());
}
}
运行结果:age:18,name:jack,email:123@123.com
19