this关键字
在Java开发中,当成员变量与局部变量发生重名问题时,需要使用到this关键字分辨成员变量与局部变量,
Java中的this关键字语法比较灵活,其主要作用主要有以下3种。
(1)使用this关键字调用本类中的属性。
(2)this关键字调用成员方法。
(3)使用this关键字调用本类的构造方法。
使用this关键字调用本类中的属性
在类的构造方法中,如果参数名称与类属性名称相同,则会导致成员变量和局部变量的名称冲突。
错误示范
class Student {
private String name;
private int age;
public Student(String name, int age) {
name = name;
age = age;
}
public String read(){
return "我是:"+name+"年龄"+age;
}
}
public class Example09 {
public static void main(String[] args) {
Student stu =new Student("张三",18);
System.out.println(stu.read());
}
}
正确示范
public class Student {
private String name;
private int age;
public Student(String name, int age) {
this. name = name;
this. age = age;
}
public String read(){
return "我是:"+name+"年龄"+age;
}
}
public class Example10 {
public static void main(String[] args) {
Student stu =new Student("张三",18);
System.out.println(stu.read());
}
}
ps:在构造方法之中,使用this关键字明确标识出了类中的两个属性“this.name”和“this.age”,所以在进行赋值操作时不会产生歧义。
使用this关键字调用成员方法
通过this关键字调用成员方法,具体示例代码如下:
class Student {
public void openMouth() {
...
}
public void read() {
this.openMouth();
}
使用this关键字调用构造方法
在使用this调用类的构造方法时,应注意以下几点:
(1)只能在构造方法中使用this调用其他的构造方法,不能在成员方法中通过this调用其他构造方法。
(2)在构造方法中,使用this调用构造方法的语句必须位于第一行,且只能出现一次。
(3)不能在一个类的两个构造方法中使用this互相调用