1.什么是this
this主要存在于
(1)构造器中:表示当前创建的对象
(2)方法中:表示哪个对象就调用this所在的方法,就表示哪个对象
package HelloWorld;
class user {
private String userName; //姓名
private Integer age; //年龄
private String addes; //住址
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getAddes() {
return addes;
}
public void setAddes(String addes) {
this.addes = addes;
}
@Override
public String toString() {
return "user [userName=" + userName + ", age=" + age + ", addes=" + addes + "]";
}
}
public class userDemo {
public static void main(String[] args) {
user user1=new user();
user1.setUserName("张三");
user1.setAddes("河南");
user1.setAge(52);
System.out.println( user1.toString());
}
}
当一个对象被创建之后,就会产生一个this
user1:存在栈中
username,age等存在堆中
2.使用this常见
(1)解决成员变量与参数(局部变量)之间的二义性,必须使用
package HelloWorld;
class user {
private String addes; //住址
public String getAddes() {
return addes;
}
public void setAddes(String addes) {
this.addes = addes;
}
(2)同类中实例方法的相互调用
public String toString() {
return "user [userName=" + userName + ", age=" + age + ", addes=" + addes + "]";
}
public void hello() {
System.out.println("........");
this.toString();
}
(3)将当前对象作为参数传递给另个方法
public boolean matches(String regex) {
return Pattern.matches(regex, this);
}
(4)将当前对象作为方法的返回值(链式编程)
public synchronized StringBuffer append(Object obj) {
toStringCache = null;
super.append(String.valueOf(obj));
return this;
}
(5)构造器重载的互调,this(参数)必须写在方法第一行
user(){
}
user(String userName){
this.userName=userName;
}
user(String userName,Integer age){
this(userName) //必须为第一行且只能使用一次
this.age=age;
}
(6)static不能与this同时使用
static 优先于对象,而this随对象创建即static加载进JVM对象还没产生