public class Demo {
public int x = 10;
public int y = 15;
public void sum() {
int z = this.x + this.y;
System.out.println("x + y = " + z);
}
public static void main(String[] args) {
Demo obj = new Demo();
obj.sum();
}
}
运行结果:x + y = 25。没有重名时,写成 x + y 也行,编译器会默认把成员和 this 绑在一起。
二、区分同名变量
形参作用域是整个方法体,属于局部变量。构造方法里形参和成员同名时,直接写 name 访问到的是形参;要给成员赋值,必须写 this.name。
public class Demo {
public String name;
public int age;
public Demo(String name, int age) {
this.name = name;
this.age = age;
}
public void say() {
System.out.println("网站的名字是" + name + ",已经成立了" + age + "年");
}
public static void main(String[] args) {
Demo obj = new Demo("新华苑", 3);
obj.say();
}
}
运行结果:网站的名字是新华苑,已经成立了3年。say() 里没有同名局部变量,写 name 或 this.name 效果相同。
public class Demo {
public String name;
public int age;
public Demo() {
this("新华苑", 3);
}
public Demo(String name, int age) {
this.name = name;
this.age = age;
}
public void say() {
System.out.println("网站的名字是" + name + ",已经成立了" + age + "年");
}
public static void main(String[] args) {
Demo obj = new Demo();
obj.say();
}
}
运行结果同样是:网站的名字是新华苑,已经成立了3年。三条硬规则:
调用必须放在构造方法最起始的位置。
不能在构造方法以外调用构造方法(不能写 this() 当普通方法用)。
一个构造方法里只能调用一个构造方法;this() 和 super() 不能同时出现。
上面用到了方法重载:同名方法只要参数列表不同就可以共存,后续章节会展开。
四、作为参数传递
需要把当前对象交给另一个完全独立的类时,把 this 当作参数即可。
public class Demo {
public static void main(String[] args) {
new A();
}
}
class A {
public A() {
new B(this).print(); // 匿名对象
}
public void print() {
System.out.println("Hello from A!");
}
}
class B {
A a;
public B(A a) {
this.a = a;
}
public void print() {
a.print();
System.out.println("Hello from B!");
}
}
运行结果:
Hello from A!
Hello from B!
匿名对象就是没有名字的对象。只用一次时,new B(this).print() 等价于先 new B(this) 再立刻调用 print()。
一句话总结:this 就是当前实例;重名时用 this. 成员,构造里用 this() 转调另一个构造,需要把自己交给别人时把 this 当参数传出去。