《Java编程思想》学习笔记(四)——this总结

用法一:引用当前对象的成员变量:如果在类的方法中定义了与类的成员变量同名的局部变量, 则在该方法中,类的成员变量会被覆盖,为了在该方法中引用类的成员变量,则用到了this,例如:
package com.exercise;

public class Test {

/**
*
@param args
*/
int i = 0;

public void print() {
int i = 1;
System.out.println(i);
System.out.println(
this.i);
}

public static void main(String[] args) {
// TODO Auto-generated method stub
Test test = new Test();
test.print();
}

}
用法二:将当前对象作为参数传递:有时候,在类的某一个方法中需要调用一个外部方法,该方法的参数是该类的对象,这种情况下,调用时便可将this传递进去。例如:
class Person {
public void eat(Apple apple) {
Apple peeled
= apple.getPeeled();
System.out.println(
"Yummy");
}
}

class Peeler {
static Apple peel(Apple apple) {
//... remove peel
return apple; // Peeled
}
}

class Apple {
Apple getPeeled() {
return Peeler.peel(this);
}
}

public class PassingThis {
public static void main(String[] args) {
new Person().eat(new Apple());
}
}
用法三:在类的重载构造函数中调用其他构造函数:当一个类有多个构造函数时,为了增加代码的复用,可以在一个构造函数中调用其他构造函数,但,只允许在当前构造函数中的第一句调用一次其他构造函数,否则将无法编译通过,如下面代码所示:
package com.exercise;

public class Test {

public int i;
Test(
int i) {
this.i = i;
}
Test(String s) {
System.
out.println(s);
}
Test(
int i, String s) {
this(s);
//this(i); 编译无法通过
this.i = i;
}
public static void main(String[] args) {
Test test
= new Test(6, "Hello");
System.
out.println(test.i);
}
}
用法四:在内部类或匿名类中的用法,还未接触,待补充
注意:1、this不能用在static方法里  2、在构造函数中通过this调用其他构造函数的时候只能放在第一句
posted @ 2011-06-26 10:15  Pickuper  阅读(1341)  评论(1编辑  收藏  举报