Java-this
指代对象,指代当前对象,当前new的对象
1)在构造器的首行通过this(参数列表)调用本类中的其他构造器
2)区分局部与成员变量同名问题
如果出现同名的局部与成员变量,默认就近原则
想要调用成员,通过this.调用
如果没有出现同名的局部与成员变量,找成员可以省略this.
如果在构造器中使用this,默认指代当前new的对象
在成员方法中this默认指代当前调用成员方法的对象
注意 :
1.不能多个构造器之间通过this(参数)相互调用
2.在被static修饰的方法中不能使用this
代码
public class Calculator {
public static void main(String[] args) {
Person1 p = new Person1("张三");
System.out.println(p.name);
System.out.println("p---->"+p);
p.test();
}
}
class Person1{
public String name;
public int age;
public boolean gender;
public Person1(){
System.out.println("空构造");
System.out.println(name);
}
public Person1(String name){
this();
this.name = name;
System.out.println("一个参数构造");
System.out.println("this---->"+this);
}
public Person1(String name,int age){
System.out.println("二个参数构造");
this.name = name;
this.age = age;
}
public Person1(String personName,int personAge,boolean personGender){
this(personName,personAge);
gender = personGender;
System.out.println("三个参数构造");
}
public void test(){
int age = 100;
System.out.println(age); //局部
System.out.println(this.age); //成员
System.out.println(this);
}
}