this在内部获得当前对象的引用时调用:

(1) return返回当前对象;

(2) 构造器调用还有一个构造器, 带參数;

(3) 參数的名称和数据成员的名称同样;

注意:

this构造器在方法中仅仅能调用一次;

非构造器不能调用带參数的this.

//:Flower.java
/**
* 构造器
*
* Created by C.L.Wang on 15/7/12.
*/
public class Flower {
int petalCount = 0;
String s = "initial value";
Flower(int petals) {
petalCount = petals;
System.out.println("int arg only, petalCount = " + petalCount);
}
Flower(String ss) {
s = ss;
System.out.println("String arg only, petalCount = " + s);
}
Flower(String s, int petals) {
this(petals);
this.s = s;
System.out.println("String & int args");
}
Flower() {
this("hi", 47);
System.out.println("default construction (no args)");
}
void printPetalCount() {
System.out.println("petalCount = " + petalCount + " s = " + s);
}
public static void main(String[] args) {
Flower x = new Flower();
x.printPetalCount();
}
}
/**
* Output:
int arg only, petalCount = 47
String & int args
default construction (no args)
petalCount = 47 s = hi
*///:~

Java - this的使用方法-LMLPHP

05-26 18:02