更新時(shí)間:2022-04-14 09:31:40 來源:動(dòng)力節(jié)點(diǎn) 瀏覽2909次
構(gòu)造函數(shù)在創(chuàng)建對(duì)象時(shí)對(duì)其進(jìn)行初始化。它與其類同名,并且在語(yǔ)法上類似于方法。但是,構(gòu)造函數(shù)沒有明確的返回類型。
通常,您將使用構(gòu)造函數(shù)為類定義的實(shí)例變量賦予初始值,或執(zhí)行創(chuàng)建完整對(duì)象所需的任何其他啟動(dòng)過程。
所有的類都有構(gòu)造函數(shù),不管你定義與否,因?yàn)?Java 自動(dòng)提供了一個(gè)默認(rèn)構(gòu)造函數(shù),它將所有成員變量初始化為零。但是,一旦定義了自己的構(gòu)造函數(shù),就不再使用默認(rèn)構(gòu)造函數(shù)。
以下是構(gòu)造函數(shù)的語(yǔ)法
class ClassName {
ClassName() {
}
}
Java允許兩種類型的構(gòu)造函數(shù),即
無參數(shù)構(gòu)造函數(shù)
參數(shù)化構(gòu)造函數(shù)
由于名稱指定 Java 的無參數(shù)構(gòu)造函數(shù)不接受任何參數(shù),因此使用這些構(gòu)造函數(shù),方法的實(shí)例變量將使用所有對(duì)象的固定值進(jìn)行初始化。
例子
Public class MyClass {
Int num;
MyClass() {
num = 100;
}
}
您將調(diào)用構(gòu)造函數(shù)來初始化對(duì)象,如下所示
public class ConsDemo {
public static void main(String args[]) {
MyClass t1 = new MyClass();
MyClass t2 = new MyClass();
System.out.println(t1.num + " " + t2.num);
這將產(chǎn)生以下結(jié)果
100 100
大多數(shù)情況下,您將需要一個(gè)接受一個(gè)或多個(gè)參數(shù)的構(gòu)造函數(shù)。參數(shù)添加到構(gòu)造函數(shù)的方式與添加到方法的方式相同,只需在構(gòu)造函數(shù)名稱后的括號(hào)內(nèi)聲明它們即可。
例子
這是一個(gè)使用構(gòu)造函數(shù)的簡(jiǎn)單示例
// A simple constructor.
class MyClass {
int x;
// Following is the constructor
MyClass(int i ) {
x = i;
}
}
您將調(diào)用構(gòu)造函數(shù)來初始化對(duì)象,如下所示
public class ConsDemo {
public static void main(String args[]) {
MyClass t1 = new MyClass( 10 );
MyClass t2 = new MyClass( 20 );
System.out.println(t1.x + " " + t2.x);
}
}
這將產(chǎn)生以下結(jié)果
10 20
相關(guān)閱讀
0基礎(chǔ) 0學(xué)費(fèi) 15天面授
有基礎(chǔ) 直達(dá)就業(yè)
業(yè)余時(shí)間 高薪轉(zhuǎn)行
工作1~3年,加薪神器
工作3~5年,晉升架構(gòu)
提交申請(qǐng)后,顧問老師會(huì)電話與您溝通安排學(xué)習(xí)
初級(jí) 202925
初級(jí) 203221
初級(jí) 202629
初級(jí) 203743