Java中关键词this来指代当前对象,用于访问方法中访问对象的其他成员。
1.this关键字调用成员变量
通过this关键字调用成员变量,解决与成员变量名称冲突问题。
#使用方法
this.变量名
class Person{
private int age; //成员变量
private String name;
public Person(int age, String name) {
//this.age访问的时成员变量age,等号后的age访问的时局部变量age,即方法中传进来的值age
this.age = age;
this.name = name;
}
}
2.this关键字调用成员方法
#使用方法
this.方法名
#在下面的例子中,使用了this关键字调用了openMouth()方法,但是此处的this关键字可以省略不写,即
this.openMouth()和openMouth()的效果是一样的。
class Person{
public void openMouth(){
System.out.println("张开醉");
}
public void eat(){
System.out.println("吃饭先张开醉");
this.openMouth(); //或者openMouth();
System.out.println("吃饭");
}
}
public class test {
public static void main(String[] args) {
Person person = new Person();
person.eat();
}
}
3.this关键字调用构造方法
构造方法是在实例化对象的时候被Java虚拟机自动调用的,在程序中不能像调用其他方法一样去调用构造方法。但是可以在一个构造方法中使用this关键字来调用其他的构造方法。
形式:
this([参数1,参数2,...])
class Person{
private int age;
private String name;
public Person() {
this("张三");
System.out.println("无参构造函数");
}
public Person(int age) {
this();
System.out.println("age构造函数");
}
public Person(String name) {
this(18,"张三");
System.out.println("name构造函数");
this.name = name;
}
public Person(int age, String name) {
System.out.println("age,name构造函数");
}
}
public class test {
public static void main(String[] args) {
Person person = new Person(18);//实例化对象的会根据形式找到相应的构造函数
}
}
注意:
①只能在构造方法中使用this调用其他的构造方法,不能在成员方法中使用
②在构造方法中,使用this调用构造方法的语句必须是该方法的第一条执行语句,且只能出现一次。如下的写法是错误的。
③不能在一个类的两个构造方法中使用this相互调用。如下也是错误的。。
class Person{
private int age;
private String name;
public Person() {
this(17);
System.out.println("无参构造函数");
}
public Person(int age) {
this();
System.out.println("age构造函数");
}
}