Java总的this关键字只能在方法内部使用,可为已经调用了这个方法的那个对象生成相应的句柄。可以象对待其他任何对象句柄一样对待这个句柄。
特殊用法: 在构建器里调用构建器
如果一个类中定义了多个构建器,有时需要在一个构建器中调用另一个构建器,以免写重复代码。可以用this关键字做到这一点。 在一个构建器中使用this时,如果为其赋予一个自变量列表,那么 this关键字 会有不同的含义:它会对那个自变量列表相符的构建器进行明确的调用。这样,就可以直接调用其他构建器。如下:
[color=bule] //: c04:Flower.java // Calling constructors with "this."
public class Flower { int petalCount = 0; String s = new String("null"); Flower(int petals) { petalCount = petals; System.out.println( "Constructor w/ int arg only, petalCount= " + petalCount); } Flower(String ss) { System.out.println( "Constructor w/ String arg only, s=" + ss); s = ss; } Flower(String s, int petals) { this(petals); //! this(s); // Can't call two! this.s = s; // Another use of "this" System.out.println("String & int args"); } Flower() { this("hi", 47); System.out.println( "default constructor (no args)"); } void print() { //! this(11); // Not inside non-constructor! System.out.println( "petalCount = " + petalCount + " s = "+ s); } public static void main(String[] args) { Flower x = new Flower(); x.print(); } } ///:~ [/color]
可以看到,尽管可以用this调用一个构建器,但不能调用两个(构建器调用后就已经生成对象了)。另外,由于自变量S的名字以及成员数据S的名字是相同的,所以会出现混淆,可以用this.s来引用成员数据,以解决这个问题。 | |