1.当成员变量和局部变量重名时,在方法中使用this时,表示的是该方法所在类中的成员变量。(this是当前对象自己)
/**
* Created by lenovo on 2016/3/11.
* 当成员变量和局部变量同名时,可以用关键字this进行区分
* this:代表对象 (当前对象)
* this就是所在函数所属对象的引用
*/
class Person
{
private String name;//为成员变量 在堆中存在
private int age;
Person(String name)//name为局部变量 在栈里存在
{
this.name=name;//没有this的话 进栈后有个局部变量name 此时的name和堆中的没有关系 只不过将栈里的name赋给了自己
//this.name为成员变量 在堆中存在
}
//构造函数用于对象初始化
public void speak(){
System.out.println(name + ":" + age);
}
}
public class Demo1 {
public static void main(String[] args)
{
Person p=new Person("Lily");
p.speak();
}
}
2.this也可以用于在构造函数中调用其他构造函数
/*只能定义在构造函数的第一行 初始化动作必须首先执行
值得注意的是:
1:在构造调用另一个构造函数,调用动作必须置于最起始的位置。
2:不能在构造函数以外的任何函数内调用构造函数。
3:在一个构造函数内只能调用一个构造函数。
*/
class Person
{
private String name;//为成员变量 在堆中存在
private int age;
Person()
{
//this("haha");//调用Person(String name)方法
name="baby";
age=3;
System.out.println("Person run");
}
Person(String name)//name为局部变量 在栈里存在
{
this();//直接调用Person()方法
this.name=name;
}
//构造函数用于对象初始化
Person(String name,int age)
{
//this.name=name;
this(name);//在这里找到参数值为String的构造函数
this.age=age;
}
public void speak(){
System.out.println(name + ":" + age);
}
}
3把自己当作参数传递时,也可以用this.(this作当前参数进行传递)
classA {
publicA() {
newB(this).print();//调用B的方法
}
publicvoidprint() {
System.out.println("HelloAA from A!"); 3 HelloAA from A!
}
}
classB {
Aa;
publicB(A a) {
this.a= a;
}
publicvoidprint() {
a.print();//调用A的方法 1 HelloAA from A! 4 HelloAA from A!
System.out.println("HelloAB from B!"); 2 HelloAB from B! 5 HelloAB from B!
}
}
publicclassHelloA {
publicstaticvoidmain(String[] args) {
A aaa =new A();
aaa.print();
B bbb =new B(aaa);
bbb.print();
}
}
结果为:
1 HelloAA from A!
2 HelloAB from B!
3 HelloAA from A!//aaa.print();
4 HelloAA from A!
5 HelloAB from B!
在这个例子中,对象A的构造函数中,用new B(this)把对象A自己作为参数传递给了对象B的构造函数。
4 有时候,我们会用到一些内部类和匿名类,如事件处理。当在匿名类中用this时,这个this则指的是匿名类或内部类本身。这时如果我们要使用外部类的方法和变量的话,则应该加上外部类的类名。如:
public class HelloB {
int i = 1;
public HelloB() {
Thread thread = new Thread() {
public void run() {
for (int j=0;j<20;j++) {
HelloB.this.run();//调用外部类的方法
try {
sleep(1000);
} catch (InterruptedException ie) {
}
}
}
}; // 注意这里有分号
thread.start();
}
public void run() {
System.out.println("i = " + i);
i++;
}
public static void main(String[] args) throws Exception {
new HelloB();
}
}
在上面这个例子中, thread是一个匿名类对象,在它的定义中,它的run函数里用到了外部类的run函数。这时由于函数同名,直接调用就不行了。这时有两种办法,一种就是把外部的run函数换一个名字,但这种办法对于一个开发到中途的应用来说是不可取的。那么就可以用这个例子中的办法用外部类的类名加上this引用来说明要调用的是外部类的方法run。
5this同时传递多个参数
publicclassTestClass {
intx;
inty;
staticvoidshowtest(TestClass tc) {//实例化对象
System.out.println(tc.x+" "+ tc.y);
}
voidseeit() {
showtest(this);
}
publicstaticvoidmain(String[] args) {
TestClass p =newTestClass();
p.x= 9;
p.y= 10;
p.seeit();
}
}
代码中的showtest(this),这里的this就是把当前实例化的p传给了showtest()方法,从而就运行了
网友评论