总结:
1.调用构造器
2.引用成员数据
3.返回当前对象的句柄
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| public class Flower { private int petalCount = 0; private String s = new String("null"); Flower(int petals){ petalCount = petals; } Flower(String ss){ s = ss; } Flower(String ss, int petals){ this(petals); //this的一种用法 //this(ss); //可用this调用一个构造器,但不能调用两个 this.s = ss; //this的另一种用法 } Flower(){ this("hi",47);//使用默认无参构造器实现初始化; } }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| 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();//out: i = 3 } }
|