标签:
package weiguoyuan.chainunicom.cn;
public class TestThis { private String name; private int age; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public TestThis(String name,int age){ name = name; age = age; System.out.println(name + age); } public static void main(String[] args) { TestThis t = new TestThis("123", 12); System.out.println(t.getName()); System.out.println(t.getAge()); } }
必须使用this的情况
1.参数名和属性名相同时
这里 t.getName() t.getAge() 输出的是 null和0
public TestThis(String name,int age){
name = name;
age = age;
System.out.println(name + age);
因为name = name;age = age;是恒等式,
TestThis(String name,int age)这里的name age是局部变量屏蔽了类的属性 name age 所以并没有给调用这个构造函数的对象赋值
这就体现了this的作用
this.name = name;
this.age = age;
this 表示的是当前对象,即哪个对象调用的就是哪个对象
2. 构造函数重载调用 this(name) 构造函数不可以Student(name);这么调用
public TestThis(String name){ this.name = name; }
public TestThis(String name,int age){
this(name);//Student(name);
this.age = age;
System.out.println(name + age);
}
3. this作为对象参数传递
class A {
private void creatB(){
B b = new B(this);//这个this是A的对象
}
}
class B {
private A a;
public B(A a){
this.a = a;
}
}
标签:
原文地址:http://www.cnblogs.com/weixiaole/p/4522698.html