1.区分局部变量和成员变量
package com.alibaba.cn;
public class TestThisKeyword {
public static void main(String[] args) {
Person person = new Person(12,98.0,"男");
System.out.println(person.toString());
}
}
package com.alibaba.cn;
public class Person {
private int age;
private double score;
private String sex;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public double getScore() {
return score;
}
public void setScore(double score) {
this.score = score;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public Person(){
}
/*
* 局部变量传入的参数名称和类中的成员变量名称一致,这就需要使用this关键字来区分,结果为:
* Person{age=12, score=98.0, sex='男'}
* 如果不用this关键字的话,成员变量就没有赋值成功,打印结果为默认值
* Person{age=0, score=0.0, sex='null'}
* */
public Person(int age,double score,String sex){
// this.age = age;
// this.score = score;
// this.sex = sex;
age = age;
score = score;
sex = sex;
}
@Override
public String toString() {
return "Person{" +
"age=" + age +
", score=" + score +
", sex='" + sex + '\'' +
'}';
}
}
this关键字还可以用来调用构造方法
package com.alibaba.cn;
public class TestThisKeyword {
public static void main(String[] args) {
Person person = new Person(12,98.0,"男");
System.out.println(person.toString());
}
}
package com.alibaba.cn;
public class Person {
private int age;
private double score;
private String sex;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public double getScore() {
return score;
}
public void setScore(double score) {
this.score = score;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public Person(){
}
public Person(int age,double score,String sex){
// this关键字也可以用来调用构造方法,实现代码的复用,结果为:Person{age=12, score=98.0, sex='男'}
this(age,score);
this.sex = sex;
}
public Person(int age,double score){
this.age = age;
this.score = score;
}
@Override
public String toString() {
return "Person{" +
"age=" + age +
", score=" + score +
", sex='" + sex + '\'' +
'}';
}
}