更新時間:2022-08-23 10:39:59 來源:動力節(jié)點 瀏覽1230次
在Java教程中大家會學(xué)到構(gòu)造函數(shù),構(gòu)造函數(shù)在創(chuàng)建對象時對其進行初始化。它與其類同名,并且在語法上類似于方法。但是,構(gòu)造函數(shù)沒有明確的返回類型。
通常,您將使用構(gòu)造函數(shù)為類定義的實例變量賦予初始值,或執(zhí)行創(chuàng)建完整對象所需的任何其他啟動過程。
所有的類都有構(gòu)造函數(shù),不管你定義與否,因為 Java 自動提供了一個默認構(gòu)造函數(shù),它將所有成員變量初始化為零。但是,一旦定義了自己的構(gòu)造函數(shù),就不再使用默認構(gòu)造函數(shù)。
以下是構(gòu)造函數(shù)的語法
class ClassName {
ClassName() {
}
}
Java允許兩種類型的構(gòu)造函數(shù),即
無參數(shù)構(gòu)造函數(shù)
參數(shù)化構(gòu)造函數(shù)
由于名稱指定 Java 的無參數(shù)構(gòu)造函數(shù)不接受任何參數(shù),因此使用這些構(gòu)造函數(shù),方法的實例變量將使用所有對象的固定值進行初始化。
例子
Public class MyClass {
Int num;
MyClass() {
num = 100;
}
}
您將調(diào)用構(gòu)造函數(shù)來初始化對象,如下所示
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ù)情況下,您將需要一個接受一個或多個參數(shù)的構(gòu)造函數(shù)。參數(shù)添加到構(gòu)造函數(shù)的方式與添加到方法的方式相同,只需在構(gòu)造函數(shù)名稱后的括號內(nèi)聲明它們即可。
例子
這是一個使用構(gòu)造函數(shù)的簡單示例
// A simple constructor.
class MyClass {
int x;
// Following is the constructor
MyClass(int i ) {
x = i;
}
}
您將調(diào)用構(gòu)造函數(shù)來初始化對象,如下所示
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)于“淺析Java中的構(gòu)造函數(shù)”的介紹,大家如果想了解更多相關(guān)知識,可以關(guān)注一下動力節(jié)點的Java在線學(xué)習(xí),里面的課程內(nèi)容從入門到精通,細致全面,很適合沒有基礎(chǔ)的小伙伴學(xué)習(xí),希望對大家能夠有所幫助哦。
相關(guān)閱讀