您好,登錄后才能下訂單哦!
Java中如何使用無(wú)參構(gòu)造函數(shù),針對(duì)這個(gè)問(wèn)題,這篇文章詳細(xì)介紹了相對(duì)應(yīng)的分析和解答,希望可以幫助更多想解決這個(gè)問(wèn)題的小伙伴找到更簡(jiǎn)單易行的方法。
一 點(diǎn)睛
1 如果一個(gè)類沒(méi)有定義任何構(gòu)造函數(shù),那么該類會(huì)自動(dòng)生成1個(gè)默認(rèn)的構(gòu)造函數(shù)。默認(rèn)構(gòu)造函數(shù)沒(méi)有參數(shù)。
2 如果一個(gè)類定義了構(gòu)造函數(shù),但這些構(gòu)造函數(shù)都有參數(shù),那么不會(huì)生成默認(rèn)構(gòu)造函數(shù),也就是說(shuō)此時(shí)類沒(méi)有無(wú)參的構(gòu)造函數(shù)。
通過(guò)兩個(gè)例子來(lái)說(shuō)明。
二 使用無(wú)參構(gòu)造函數(shù)的錯(cuò)誤
1 代碼
public class ConstructWithNoPara{ public static void main( String[] args ) { Person p = new Person(); // 此行有錯(cuò)誤,沒(méi)有不含參數(shù)的構(gòu)造函數(shù) p.talk(); }}class Person{ private String name; private int age; public Person( int age ) { name = "Yuhong"; this.age = age; } public Person( String name, int age ) { this.name = name; this.age = age; } public void talk() { System.out.println( "我叫:" + name + " 我今年:" + age + "歲" ); }}
2 運(yùn)行
Exception in thread "main" java.lang.Error: Unresolved compilation problem: The constructor Person() is undefined at ConstructWithNoPara.main(ConstructWithNoPara.java:18)
三 正確使用無(wú)參構(gòu)造函數(shù)
1 代碼
public class ConstructOverload{ public static void main( String[] args ) { Person p = new Person(); p.talk(); }}class Person{ private String name; private int age; public Person() { name = "cakin"; age = 22; } public Person( int age ) { name = "kehr"; this.age = age; } public Person( String name, int age ) { this.name = name; this.age = age; } public void talk() { System.out.println( "我叫:" + name + " 我今年:" + age + "歲" ); }}
2 運(yùn)行
我叫:cakin 我今年:22歲
關(guān)于Java中如何使用無(wú)參構(gòu)造函數(shù)問(wèn)題的解答就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,如果你還有很多疑惑沒(méi)有解開(kāi),可以關(guān)注億速云行業(yè)資訊頻道了解更多相關(guān)知識(shí)。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。