您的位置:首页 > 其它

this 关键字的功用-显示调用构造函数。

2015-04-05 00:00 288 查看
摘要: 最近觉得要读读书,了解Java更深层的原理。于是每天花时间读读《think in java》希望有更多的收获。

Calling constructors from constructors

sited by<THINK IN JAVA> p118
When you write several constructors for a class, there are times when you’d like to call one

constructor from another to avoid duplicating code.

当你为一个类写了好几个构造函数,有时候你需要在一个构造函数中去调用另外一个构造函数来避免重复写代码。
You can make such a call by using the this keyword.

这个时候你可以通过调用THIS关键字来完成。
Normally, when you say this, it is in the sense of “this object” or “the current object,” and by
itself it produces the reference to the current object.

在通常的情况下,你说this 的时候,它都被用来表示当前的对象,产生一个对象的引用。

In a constructor, the this keyword takes on a different meaning when you give it an argument list.

可是在构造函数里面,当你给它一些形参的时候 this 关键字却可以表示另外一种含义。

It makes an explicit call to the constructor that matches that argument list.

那就是你它可以显示的调用一个和它的形参数目一样的构造方法。

Thus you have a straightforward way to call other constructors。

因此你就可以轻松自如的调用其它的构造方法。

//: initialization/Flower.java
// Calling constructors with "this"
import static net.mindview.util.Print.*;
public class Flower {
int petalCount = 0;
String s = "initial value";
Flower(int petals) {
petalCount = petals;
print("Constructor w/ int arg only, petalCount= "
+ petalCount);
}
Flower(String ss) {
print("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"
print("String & int args");
}
Flower() {
this("hi", 47);
print("default constructor (no args)");
}
void printPetalCount() {
//! this(11); // Not inside non-constructor!
print("petalCount = " + petalCount + " s = "+ s);
}
public static void main(String[] args) {
Flower x = new Flower();
x.printPetalCount();
}
} /* Output:
Constructor w/ int arg only, petalCount= 47
String & int args
default constructor (no args)
petalCount = 47 s = hi
*///:
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  this 构造函数