this的用法 this("hi", 47);this(petals);

来源:百度知道 编辑:UC知道 时间:2024/05/29 12:45:31
public class Flower {
private int petalCount = 0;
private String s = new String("null");
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(s); // Can't call two!
this.s = s; // Another use of "this"
System.out.println("String & int args");
}
Flower() {
this("hi", 47);
System.out.println(
"default constructor (no args)");
}
void print() {
//! this(11); // Not inside non-constructor!
System.out.println(
"petalCount = " + petalCount + " s = "+ s)

this放在构造方法第一句(必须也只能在第一句)是调通符合括号内参数的构造方法

this(petals);就是调用构造方法Flower(int petals)

this("hi", 47);是调用构造方法Flower(String s, int petals)

这几个this是重载