构造器:JAVA中通过构造器确保类的初始化。类的设计者可以在类创建时定义类的构造器,即使没有显示的构造构造器,JVM也会为类默认构造一个无参构造器。也可以构造多个构造器,JAVA会根据具体的情境(参数类型和数量)来选择合适的构造器—多态。
this关键字:this关键字只能在方法的内部进行调用,表示对“调用方法的那个对象”的引用。
package com.tree.thread;
class Person{
public void eat(Apple apple){
Apple peeled =apple.getpeeled();
System.out.println("YUMMY!");
}
}
class Peeler{
static Apple peel(Apple apple){
return apple;
}
}
class Apple{
Apple getpeeled(){
return Peeler.peel(this);
}
}
public class Tree {
public static void main(String[] args) {
// TODO Auto-generated method stub
new Person().eat(new Apple());
}
}
以上输出:YUMMY!Apple需要调用Peeler.peel()的方法,它是一个外部的工具方法,将执行由于某种原因而必须放在Apple外部的操作(例如该外部方法要应用许多不同的类,而你不想重复这些代码)。为了将其自身传递给外部方法,Apple必须使用this关键字。
此外,think in JAVA还有一个经典的例子。代码如下:
package com.tree.thread;
public class ThisDemo {
int number;
ThisDemo increment(){
number++;
return this;
}
private void print(){
System.out.println("number:"+number);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
new ThisDemo().increment().increment().print();
}
}
以上输出:number:2此外,如果一个类有多个构造器,有时可能现在一个构造器中调用另一个构造器,以避免重复代码。这个时候this又派上了用场。通常写this的时候,都是指“这个对象”或者“当前对象”,而且它本身表示对当前对象的引用。在构造器中,如果this后跟了参数列表,那么就有了不同的含义—这将产生对符合此参数列表的某个构造器的明确调用;这样,调用其他构造器就有了明确的途径。
需要注意的是:
(1) 必须将构造器调用置于最初始处,否则编译器会报错
(2) 尽管可以用this调用一个构造器,但不能调用两个
package com.tree.thread;
public class ThisDemo01 {
int iCount =0;
String s = "tree";
ThisDemo01(int i){
iCount = i;
System.out.println("整数构造器 i :"+i);
}
ThisDemo01(String ss){
s = ss;
System.out.println("字符串构造器 s :"+ss);
}
ThisDemo01(int i,String s){
this(i);
//this(s)两个this调用的构造器不能一起使用!
this.s = s;
System.out.println("组合构造器 i :"+i);
}
ThisDemo01(){
this(11,"wang");
System.out.println("无参构造器 ");
}
void printDemo(){
//this(11);此处使用会报错
System.out.println("iCount ="+iCount+"s =" +s);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
ThisDemo01 x = new ThisDemo01();
x.printDemo();
}
}
以上输出: