java中構(gòu)造器內(nèi)部調(diào)用構(gòu)造器實例詳解
可能為一個類寫了多個構(gòu)造器,有時可能想在一個構(gòu)造器里面調(diào)用另外一個構(gòu)造器,為了減少代碼的重復(fù),可用this關(guān)鍵字做到這一點。
public class Flower { private String string; private int age; public Flower() { // 先調(diào)用public Flower(String string, int age) this('leon', 120); // 先調(diào)用public Flower(String string, int age) } public Flower(String string) { this(string, 12); } public Flower(String string, int age) { this.string = string; this.age = age; System.out.println('姓名:' + this.string + ' 年齡: ' + this.age); } public static void main(String[] args) { Flower flower = new Flower(); Flower flower1 = new Flower('leon'); Flower flower2 = new Flower('leon', 12); }}
其實可以從結(jié)果看見,這其實可普通的函數(shù)調(diào)用沒什么區(qū)別,只不過是用了this這個關(guān)鍵字。
內(nèi)容補(bǔ)充:
構(gòu)造函數(shù)的作用
這個示例項目中的 DiceRoller 類表示一個虛擬骰子工廠:當(dāng)它被調(diào)用時,它創(chuàng)建一個虛擬骰子,然后進(jìn)行“滾動”。然而,通過編寫一個自定義構(gòu)造器,你可以讓擲骰子的應(yīng)用程序詢問你希望模擬哪種類型的骰子。
大部分代碼都是一樣的,除了構(gòu)造器接受一個表示面數(shù)的數(shù)字參數(shù)。這個數(shù)字還不存在,但稍后將創(chuàng)建它。
import java.util.Random;public class DiceRoller { private int dice; private int roll; private Random rand = new Random(); // constructor public DiceRoller(int sides) { dice = sides; }
模擬滾動的函數(shù)保持不變:
public void Roller() { roll = rand.nextInt(dice); roll += 1; System.out.println (roll);}
代碼的主要部分提供運(yùn)行應(yīng)用程序時提供的任何參數(shù)。這的確會是一個復(fù)雜的應(yīng)用程序,你需要仔細(xì)解析參數(shù)并檢查意外結(jié)果,但對于這個例子,唯一的預(yù)防措施是將參數(shù)字符串轉(zhuǎn)換成整數(shù)類型。
到此這篇關(guān)于java中構(gòu)造器內(nèi)部調(diào)用構(gòu)造器實例詳解的文章就介紹到這了,更多相關(guān)java中關(guān)于構(gòu)造器內(nèi)部調(diào)用構(gòu)造器淺談內(nèi)容請搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. ASP的Global.asa文件技巧用法2. ASP中常用的22個FSO文件操作函數(shù)整理3. html清除浮動的6種方法示例4. React+umi+typeScript創(chuàng)建項目的過程5. SharePoint Server 2019新特性介紹6. PHP函數(shù)原理理解詳談7. php網(wǎng)絡(luò)安全中命令執(zhí)行漏洞的產(chǎn)生及本質(zhì)探究8. Vue+elementUI下拉框自定義顏色選擇器方式9. ASP中if語句、select 、while循環(huán)的使用方法10. JSP數(shù)據(jù)交互實現(xiàn)過程解析
