構(gòu)造函數(shù)是一種特殊的函數(shù)。其主要功能是用來在創(chuàng)建對(duì)象時(shí)初始化對(duì)象, 即為v對(duì)象成員變量賦初始值,總與new運(yùn)算符一起使用在創(chuàng)建對(duì)象的語句中。構(gòu)造函數(shù)與類名相同,可重載多個(gè)不同的構(gòu)造函數(shù)。在JAVA語言中,構(gòu)造函數(shù)與C++語言中的構(gòu)造函數(shù)相同,JAVA語言中普遍稱之為構(gòu)造方法。
使用構(gòu)造器時(shí)需要記住:
1.構(gòu)造器必須與類同名(如果一個(gè)源文件中有多個(gè)類,那么構(gòu)造器必須與公共類同名)
2.每個(gè)類可以有一個(gè)以上的構(gòu)造器
3.構(gòu)造器可以有0個(gè)、1個(gè)或1個(gè)以上的參數(shù)
4.構(gòu)造器沒有返回值
5.構(gòu)造器總是伴隨著new操作一起調(diào)用
示例:
A.java
Java代碼
1
2
3
4
5
6
7
8
9
|
public class A{ public A(){ System.out.println( "調(diào)用了無參的構(gòu)造函數(shù)" ); } public A(String mess){ System.out.println( "調(diào)用了有參的構(gòu)造函數(shù)\n" + "參數(shù)內(nèi)容為:" +mess); } } |
Test.java
Java代碼
1
2
3
4
5
6
|
public class Test{ public static void main(String [] args){ A a_1= new A(); //調(diào)用無參的構(gòu)造函數(shù) A a_2= new A( "Hello" ); //調(diào)用有參的構(gòu)造函數(shù) } } |
輸出結(jié)果:
繼承與構(gòu)造函數(shù)
使用super調(diào)用父類構(gòu)造器的語句必須是子類構(gòu)造器的第一條語句
如果子類構(gòu)造器沒有顯式地調(diào)用父類的構(gòu)造器,則將自動(dòng)調(diào)用父類的默認(rèn)(沒有參數(shù))的構(gòu)造器。如果父類沒有不帶參數(shù)的構(gòu)造器,并且在子類的構(gòu)造器中又沒有顯式地調(diào)用父類的構(gòu)造器,則java編譯器將報(bào)告錯(cuò)誤
示例:
A.java
Java代碼
1
2
3
4
5
6
7
8
9
|
public class A{ public A(){ System.out.println( "調(diào)用了A的無參構(gòu)造函數(shù)" ); } public A(String mess){ System.out.println( "調(diào)用了A的有參的構(gòu)造函數(shù)\n" + "參數(shù)內(nèi)容為:" +mess); } } |
B.java
Java代碼
1
2
3
4
5
6
7
8
9
10
|
public class B extends A{ public B(){ System.out.println( "調(diào)用了B的無參構(gòu)造函數(shù)" ); } public B(String mess){ super (mess); System.out.println( "調(diào)用了B的有參構(gòu)造函數(shù)\n" + "參數(shù)內(nèi)容為:" +mess); } } |
Test.java
Java代碼
1
2
3
4
5
6
|
public class Test{ public static void main(String [] args){ B b_01= new B(); B b_02= new B( "你好" ); } } |
輸出結(jié)果:
以上所述是小編給大家介紹的Java構(gòu)造方法實(shí)例詳解(動(dòng)力節(jié)點(diǎn)java學(xué)院整理),希望對(duì)大家有所幫助,如果大家有任何疑問請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)服務(wù)器之家網(wǎng)站的支持!