this 关键字 (二)

来源:互联网 发布:js 中 json点不出来 编辑:程序博客网 时间:2024/05/01 02:27
若为一个类写了多个构建器,那么经常都需要在一个构建器里调用另一个构建器,以避免写重复的代码。可
用this 关键字做到这一点。 
通常,当我们说this 的时候,都是指“这个对象”或者“当前对象”。而且它本身会产生当前对象的一个句
柄。在一个构建器中,若为其赋予一个自变量列表,那么 this 关键字会具有不同的含义:它会对与那个自变
量列表相符的构建器进行明确的调用。这样一来,我们就可通过一条直接的途径来调用其他构建器。如下所

示: 

 
//: Flower.java 
// Calling constructors with "this" 
 
public class Flower { 
  private int petalCount = 0; 
  private 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(); 
  } 
} ///:~ 

其中,构建器Flower(String s,int petals)向我们揭示出这样一个问题:尽管可用this 调用一个构建器,
但不可调用两个。除此以外,构建器调用必须是我们做的第一件事情,否则会收到编译程序的报错信息。 
这个例子也向大家展示了this 的另一项用途。由于自变量s 的名字以及成员数据s 的名字是相同的,所以会
出现混淆。为解决这个问题,可用 this.s来引用成员数据。经常都会在 Java 代码里看到这种形式的应用,
本书的大量地方也采用了这种做法。 
在print()中,我们发现编译器不让我们从除了一个构建器之外的其他任何方法内部调用一个构建器。 
 

0 0