Chapter5_初始化与清理_this关键字

时间:2023-03-09 17:01:23
Chapter5_初始化与清理_this关键字

  this关键字是Java中一类很特殊的关键字,首先它只能在方法内使用,用来表示调用这个方法的对象,在这一点上this和其他对对象的引用的操作是相同的。我们之所以可以在方法内部访问到它是因为编译器在方法调用时,会将调用方法的对象作为第一个参数传到方法里面。下面列举几个例子来对this的用途做一些总结。

  (1)作为返回值,返回当前对象的引用,在一条语句里对同一个对象做多次操作。  

 class leaf{
int count; public leaf(){
count = 0;
} public leaf increse(){
count++;
return this;
}
} public class test {
public static void main(String[] args){
leaf l = new leaf();
l.increse().increse().increse();
System.out.println(l.count);
}
}

  (2)将自身传递给外部的方法,用于代码复用

 class sculpture{
String done; public sculpture getSculped(){
return sculptor.make(this);
} public void info(){
System.out.println(done);
}
} class sculptor{
public static sculpture make(sculpture s){
s.done = "yes";
return s;
}
} public class test {
public static void main(String[] args){
new sculpture().getSculped().info();
}
}

  这段代码实现的事情是,每一个sculpture(雕塑)都可以调用自己的getSculped方法,把自己传给sculptor(雕塑家)的一个静态方法,来完成雕塑。这样做的好处是每一个sculpture都可以调用外部方法,来完成雕塑的过程,实现对代码的复用。

  (3)在构造器中调用构造器

 class footballteam{
int count; public footballteam(){
this(23);
} public footballteam(int count){
this.count = count;
} public void info(){
//this(22);报错!
System.out.println("we have " + count + " players");
}
} public class test {
public static void main(String[] args){
footballteam rma = new footballteam();
rma.info();
}
}

  程序的第五行在默认构造器中调用了一次带参数的构造器,这样可以有不同的调用构造器的方法。另外13行的出错信息告诉我们,不能在除构造器之外的方法内调用构造器。