教育行業(yè)A股IPO第一股(股票代碼 003032)

全國(guó)咨詢/投訴熱線:400-618-4000

怎樣使用?this關(guān)鍵字調(diào)用本類?【案例演示】

更新時(shí)間:2021年10月18日14時(shí)49分 來(lái)源:傳智教育 瀏覽次數(shù):

好口碑IT培訓(xùn)

構(gòu)造方法在實(shí)例化對(duì)象時(shí)被Java虛擬機(jī)自動(dòng)調(diào)用,在程序中不能像調(diào)用其他成員方法樣調(diào)用構(gòu)造方法,但可以在一個(gè)構(gòu)造方法中使用"this(參數(shù)1,參數(shù)2...)”的形式調(diào)用其他的構(gòu)造方法。

下面通過(guò)一個(gè)案例演示使用this關(guān)鍵字調(diào)用構(gòu)造方法,如文件3-11所示。

文件3-11 Examplel1 java

class student {

private int age;

public Student ( ) {

System.out.println ("實(shí)例化了一個(gè)新的Student對(duì)象。");

}
public Student (String  name,int age) {

this ( ) ;     //調(diào)用無(wú)參的構(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);//實(shí)例化Student對(duì)象

System.out.println(stu.read ( ) ) ; 
   }
}

文件3-11的運(yùn)行結(jié)果如圖3-16所示。

文件3-11中提供了兩個(gè)構(gòu)造方法,其中,有兩個(gè)參數(shù)的構(gòu)造方法中使用this ( )的形式調(diào)用本類中的無(wú)參構(gòu)造方法。由圖3-16可知,無(wú)參構(gòu)造方法和有參構(gòu)造方法均調(diào)用成功。


在使用this調(diào)用類的構(gòu)造方法時(shí),應(yīng)注意以下幾點(diǎn)。

(1)只能在構(gòu)造方法中使用this調(diào)用其他的構(gòu)造方法,不能在成員方法中通過(guò)this調(diào)用其他構(gòu)造方法。
(2)在構(gòu)造方法中,使用this調(diào)用構(gòu)造方法的語(yǔ)句必須位于第行,且只能出現(xiàn)一次。




猜你喜歡:

final關(guān)鍵字的作用和特點(diǎn)【final關(guān)鍵字的作用詳細(xì)介紹】

Java語(yǔ)言中的關(guān)鍵字有哪些

final關(guān)鍵字修飾變量為什么會(huì)報(bào)錯(cuò)?

使用static關(guān)鍵字如何定義成員變量?

傳智教育java后端開(kāi)發(fā)工程師培訓(xùn)

0 分享到:
和我們?cè)诰€交談!