详见下图所示:
1
42
MyThisTest a=42
为输出:
第一个: 在这个方法内 a = 1;
第二个:指向的class 内的 field(形参与成员名字重名,用 this 来区分);
第三个: 指向整个对象的本身(最直接的应用)
Java 中 this 和 super 的用法总结 | 菜鸟教程;
关于菜鸟教程的问题: this.age 是成员变量即 field
this.age = age 意味着传入的形参 成为了这个对象的 field (private)
在构造函数里面的this方法:用于调用另一个具有同样形参的构造方法,可以参考菜鸟教程里面的super关键字
public class MyThisTest {
private int a;
public MyThisTest() {
this(42); // calls the other constructor
}
public MyThisTest(int a) {
this.a = a; // assigns the value of the parameter a to the field of the same name
}
public void frobnicate() {
int a = 1;
System.out.println(a); // refers to the local variable a
System.out.println(this.a); // refers to the field a
System.out.println(this); // refers to this entire object
}
public String toString() {
return "MyThisTest a=" + a; // refers to the field a
}
}
//第二个例子来自于菜鸟教程
class Person {
private int age = 10;
public Person(){
System.out.println("初始化年龄:"+age);
}
public int GetAge(int age){
this.age = age;
return this.age;
}
}
public class test1 {
public static void main(String[] args) {
Person Harry = new Person();
System.out.println("Harry's age is "+Harry.GetAge(12));
}
}