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
*///:
相关文章
相关标签/搜索