通常this在各种语言中都表示“调用当前函数的对象”,java中也存在这种用法:java
1 public class Leaf { 2 int i = 0; 3 Leaf increment(){ 4 i++; 5 return this; //this指代调用increment()函数的对象 6 } 7 void print(){ 8 System.out.println("i = " + i); 9 } 10 public static void main(String[] args) { 11 Leaf x = new Leaf(); 12 x.increment().increment().increment().print(); 13 } 14 15 } 16 //////////out put/////////// 17 //i = 3
在上面的代码中,咱们在main()函数里首先定义了Leaf类的一个对象:x 。而后经过这个对象来调用increment()方法, 在这个increment()方法中返回了this--也就是指代调用它的当前对象x (经过这种方式就实现了链式表达式的效果)。函数
咱们经过x.increment()来表示经过x来调用increment()函数,实际上在java语言内部这个函数的调用形式是这样子的:this
Leaf.increment(x);
固然,这种转换只存在与语言内部,而不能这样写码。spa
另一种状况是在构造函数中调用构造函数时,this指代一个构造函数,来看一个简单的例子:code
1 public class Flower { 2 int petalCount = 0; 3 String s = "initial value"; 4 Flower(int petals){ 5 petalCount = petals; 6 System.out.println("Constructor w/ int arg only, petalCount = " + petalCount); 7 } 8 9 Flower(String ss){ 10 System.out.println("Constructor w/ string arg only, s = " + ss); 11 s = ss; 12 } 13 14 Flower(String s, int petals){ 15 this(petals); //这里的"this"指代的Flower构造器 16 this.s = s; 17 System.out.println("string and int args"); 18 } 19 20 Flower(){ 21 this("hi", 47); //这里的"this"指代的Flower构造器 22 System.out.println("default (no args)"); 23 } 24 public static void main(String[] args) { 25 // TODO Auto-generated method stub 26 new Flower(); 27 } 28 } 29 ////////Out put///////////// 30 //Constructor w/ int arg only, petalCount = 47 31 //string and int args 32 //default (no args)
Flower类有四个构造函数,在这写构造函数内部的this表示也是Flower类的构造函数,并且this()中的参数的个数也指代对应的构造函数,这样就实现了在构造函数中调用其余的构造函数。对象
可是须要注意的一点就是:虽然咱们能够经过this在一个构造函数中调用另外一个构造函数,可是咱们顶多只能用这种方法调用一次,并且对另外一个构造函数的调用动做必须置于最起始处,不然编译器会发出错误消息。比方说,下面这样是不行的:blog
Flower(String s, int petals){ this(petals); this(s); //error! 顶多只能调用this()一次。 }