更新時間:2021-10-15 來源:黑馬程序員 瀏覽量:

構(gòu)造方法在實例化對象時被Java虛擬機自動調(diào)用,在程序中不能像調(diào)用其他成員方法樣調(diào)用構(gòu)造方法,但可以在一個構(gòu)造方法中使用"this(參數(shù)1,參數(shù)2...)”的形式調(diào)用其他的構(gòu)造方法。
下面通過一個案例演示使用this關(guān)鍵字調(diào)用構(gòu)造方法,如文件3-11所示。
文件3-11 Examplel1 java
class student {
private int age;
public Student ( ) {
System.out.println ("實例化了一個新的Student對象。");
}
public Student (String name,int age) {
this ( ) ; //調(diào)用無參的構(gòu)造方法
this.name = name;
this.age = age;
}
public String read ( ) {
return "我是:"+name+",年齡:"+age;
}
}
public class Examplell {
Public static void main(String{ )args){
Student stu = new Student(“張三”,18);//實例化Student對象
System.out.println(stu.read ( ) ) ;
}
}文件3-11的運行結(jié)果如圖3-16所示。
文件3-11中提供了兩個構(gòu)造方法,其中,有兩個參數(shù)的構(gòu)造方法中使用this ( )的形式調(diào)用本類中的無參構(gòu)造方法。由圖3-16可知,無參構(gòu)造方法和有參構(gòu)造方法均調(diào)用成功。
在使用this調(diào)用類的構(gòu)造方法時,應(yīng)注意以下幾點。
(1)只能在構(gòu)造方法中使用this調(diào)用其他的構(gòu)造方法,不能在成員方法中通過this調(diào)用其他構(gòu)造方法。
(2)在構(gòu)造方法中,使用this調(diào)用構(gòu)造方法的語句必須位于第行,且只能出現(xiàn)一次。
猜你喜歡:
詳解this關(guān)鍵字的用法【Java技術(shù)文章】