若为一个类写了多个构建器,那么经常都需要在一个构建器里调用另一个构建器,以避免写重复的代码。可用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()中,我们发现编译器不让我们从除了一个构建器之外的其他任何方法内部调用一个构建器。
闽公网安备 35060202000074号