1) 调用对象自己
2) 一个构造函数调用另一个构造函数,必须是第一条语句,并且不能调用两个以上的的构造函数。
- public class Leaf {
- private int i = 0;
- Leaf increment() {
- i++;
- return this;
- }
- void print() {
- System.out.println("i = " + i);
- }
- public static void main(String[] args) {
- Leaf x = new Leaf();
- x.increment().increment().increment().print();
- }
- }
- 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);
- }
- public static void main(String[] args) {
- Flower x = new Flower();
- x.print();
- }
- }