您的位置:首页 > 编程语言 > Java开发

初探java中this的用法

2013-11-22 11:29 405 查看
一般this在各类语言中都表示“调用当前函数的对象”,java中也存在这种用法:

public class Leaf {
int i = 0;
Leaf increment(){
i++;
return this;    //this指代调用increment()函数的对象
}
void print(){
System.out.println("i = " + i);
}
public static void main(String[] args) {
Leaf x = new Leaf();
x.increment().increment().increment().print();
}

}
//////////out put///////////
//i = 3


在上面的代码中,我们在main()函数里首先定义了Leaf类的一个对象:x 。然后通过这个对象来调用increment()方法, 在这个increment()方法中返回了this--也就是指代调用它的当前对象x (通过这种方式就实现了链式表达式的效果)。

我们通过x.increment()来表示通过x来调用increment()函数,实际上在java语言内部这个函数的调用形式是这样子的:

Leaf.increment(x);


当然,这种转换只存在与语言内部,而不能这样写码。

另外一种情况是在构造函数中调用构造函数时,this指代一个构造函数,来看一个简单的例子:

public class Flower {
int petalCount = 0;
String s = "initial value";
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"指代的Flower构造器
this.s = s;
System.out.println("string and int args");
}

Flower(){
this("hi", 47);    //这里的"this"指代的Flower构造器
System.out.println("default (no args)");
}
public static void main(String[] args) {
// TODO Auto-generated method stub
new Flower();
}
}
////////Out put/////////////
//Constructor w/ int arg only, petalCount = 47
//string and int args
//default (no args)


Flower类有四个构造函数,在这写构造函数内部的this表示也是Flower类的构造函数,而且this()中的参数的个数也指代对应的构造函数,这样就实现了在构造函数中调用其他的构造函数。

但是需要注意的一点就是:虽然我们可以通过this在一个构造函数中调用另一个构造函数,但是我们顶多只能用这种方法调用一次,而且对另一个构造函数的调用动作必须置于最起始处,否则编译器会发出错误消息。比方说,下面这样是不行的:

Flower(String s, int petals){
this(petals);
this(s);  //error! 顶多只能调用this()一次。
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: