1.this:調用本類的成員變量(不是局部變量)
public class TestStudent{
public static void main(String[] args) {
Student s = new Student("張1",35,94.2);
System.out.println("name="+s.name+"-age="+s.age+"-score="+s.score);
}
}
class Student {
String name;
int age;
double score=3.2;
public Student() {
System.out.println("Student()...");
}
public Student(String name, int age) {
System.out.println("Student(String name, int age)...");
}
public Student(String name, int age, double score) {
this.name = name;
this.age = age;
this.score = score;
System.out.println("Student(String name, int age, double score)...");
}
}
這個裏面的this表示成員變量,this.name表示成員變量name,
2.this()/this(實參):調用本類的構造方法。
public class TestStudent{
public static void main(String[] args) {
Student s = new Student("張1",35,94.2);
System.out.println("name="+s.name+"-age="+s.age+"-score="+s.score);
}
}
class Student {
String name;
int age;
double score=3.2;
public Student() {
System.out.println("Student()...");
}
public Student(String name, int age) {
this.name = name;
this.age = age;
System.out.println("Student(String name, int age)...");
}
public Student(String name, int age, double score) {
this(name,age);
this.score = score;
System.out.println("Student(String name, int age, double score)...");
}
}
在創建對象時,new分配空間,賦默認值,執行三個參數的構造方法,此時,jvm不將屬性初始化的操作移交給此構造方法,而是 執行this(name,age)(當有這個時,把再將屬性初始化移交給此構造方法),去兩個參數的構造方法,然後進行屬性初始化,再執行構造方法中的原有內容。