this 關鍵字的功用-顯示調用構造函數。

Calling constructors from constructors  java

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

constructor from another to avoid duplicating code.函數

當你爲一個類寫了好幾個構造函數,有時候你須要在一個構造函數中去調用另一個構造函數來避免重複寫代碼。
 You can make such a call by using the this keyword.
this

這個時候你能夠經過調用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.
spa

在一般的狀況下,你說this 的時候,它都被用來表示當前的對象,產生一個對象的引用。code

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

但是在構造函數裏面,當你給它一些形參的時候 this 關鍵字卻能夠表示另一種含義。對象

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

那就是你它能夠顯示的調用一個和它的形參數目同樣的構造方法。it

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
*///:
相關文章
相關標籤/搜索