站内搜索: 请输入搜索关键词

当前页面: 开发资料首页J2SE 专题在构建器里调用构建器

在构建器里调用构建器

摘要: 在构建器里调用构建器
<table cellSpacing=0 cellPadding=0 border=0 class="zh114" align="right"> <tr> <td > </td> </tr> </table>
  
  若为一个类写了多个构建器,那么经常都需要在一个构建器里调用另一个构建器,以避免写重复的代码。可用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()中,我们发现编译器不让我们从除了一个构建器之外的其他任何方法内部调用一个构建器。
  
  

<table width="96%"> <tr> <td background="http:///images/dian.gif" height="3"></td> </tr> </table>

↑返回目录
前一篇: public:接口访问
后一篇: 主类型的过载