为什么要有this关键字什么是this关键字
在认识this关键字之前我们先来了解一下为什么会有this关键字吧
当我们在编写代码的时候形参名不小心与成员变量名相同的时候
public class Person {
public String name;
public int age;
public String gender;
public void person1(String name,int age,String gender){
name = name;
age = age;
gender = gender;
}
public void show(){
System.out.println("名字:"+name+" 年龄:"+age+" 性别:"+gender);
}
}
class Invent{
public static void main(String[] args) {
Person person=new Person();
person.person1("张三",11,"男");
person.show();
}
}
此时代码打印的结果都是默认值这是为什么呢?
因为在调用的时候成员变量名与局部变量相同
局部变量(String name,int age,String gender)会被优先调用,所以就默认初始化也就打印出我们看见的结果了
那么我们又该如何解这一问题呢?
此时就引用this关键字了
public class Person {
public String name;
public int age;
public String gender;
public void person1(String name,int age,String gender){
this.name = name;
this.age = age;
this.gender = gender;
}
public void show(){
System.out.println("名字:"+name+" 年龄:"+age+" 性别:"+gender);
}
}
class Invent{
public static void main(String[] args) {
Person person=new Person();
person.person1("张三",11,"男");
person.show();
}
}
我们可以看见在这里加上this,就打印出我们想要的值了
这是为什么呢?下面我们就一起来了解一下什么是this关键字吧!
this引用指向当前对象(成员方法运行时调用该成员方法的对象),在成员方法中所有成员变量的操作,都是通过该引用去访问。只不过所有的操作对用户是透明的,即用户不需要来传递,编译器自动完成。
public void person1(String name,int age,String gender){
this.name = name;
this.age = age;
this.gender = gender;
}
注意:this引用的是调用成员方法的对象。
this关键字的特性
- this的类型:对应类类型引用,即哪个对象调用就是哪个对象的引用类型
- this只能在"成员方法"中使用
- 在"成员方法"中,this只能引用当前对象,不能再引用其他对象
- this是“成员方法”第一个隐藏的参数,编译器会自动传递,在成员方法执行时,编译器会负责将调用成员方法对象的引用传递给该成员方法,this负责来接收
this关键字的功能
1.this.person1:访问当前对象的成员方法
此时我们可以看见在成员方法中加入一个this关键字对于编译并没有影响不加也没有关系,那是因为每个成员方法第一个参数默认值是this
public void person1(Person this ,String name,int age,String gender){
this.name = name;
this.age = age;
this.gender = gender;
}
2.this.name:访问当前对象的成员变量
this.name = name;
this.age = age;
this.gender = gender;
如上面所居的例子
3.this():访问当前对象的构造方法
public class Person {
public String name;
public int age;
public String gender;
Person(String name,int age,String gender){
this.name = name;
this.age = age;
this.gender = gender;
}
public void show(){
System.out.println("名字:"+name+" 年龄:"+age+" 性别:"+gender);
}
}
class Invent{
public static void main(String[] args) {
Person person=new Person("张三",11,"男");
person.show();
}
}
注意事项
1.this() 不能使用在普通方法中 只能写在构造方法中
2.必须是构造方法中的第一条语句
Person(){
this.name="张三";
this("张三",11,"男");
}
Person(String name,int age,String gender){
this.name = name;
this.age = age;
this.gender = gender;
}
此时this()没有写在第一行编译器会报错
同样的this()写在普通方法里面编译器也会报错