java中構(gòu)造器內(nèi)部調(diào)用構(gòu)造器實(shí)例詳解
可能為一個(gè)類寫了多個(gè)構(gòu)造器,有時(shí)可能想在一個(gè)構(gòu)造器里面調(diào)用另外一個(gè)構(gòu)造器,為了減少代碼的重復(fù),可用this關(guān)鍵字做到這一點(diǎ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); }}
其實(shí)可以從結(jié)果看見,這其實(shí)可普通的函數(shù)調(diào)用沒什么區(qū)別,只不過是用了this這個(gè)關(guān)鍵字。
內(nèi)容補(bǔ)充:
構(gòu)造函數(shù)的作用
這個(gè)示例項(xiàng)目中的 DiceRoller 類表示一個(gè)虛擬骰子工廠:當(dāng)它被調(diào)用時(shí),它創(chuàng)建一個(gè)虛擬骰子,然后進(jìn)行“滾動(dòng)”。然而,通過編寫一個(gè)自定義構(gòu)造器,你可以讓擲骰子的應(yīng)用程序詢問你希望模擬哪種類型的骰子。
大部分代碼都是一樣的,除了構(gòu)造器接受一個(gè)表示面數(shù)的數(shù)字參數(shù)。這個(gè)數(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; }
模擬滾動(dòng)的函數(shù)保持不變:
public void Roller() { roll = rand.nextInt(dice); roll += 1; System.out.println (roll);}
代碼的主要部分提供運(yùn)行應(yīng)用程序時(shí)提供的任何參數(shù)。這的確會(huì)是一個(gè)復(fù)雜的應(yīng)用程序,你需要仔細(xì)解析參數(shù)并檢查意外結(jié)果,但對(duì)于這個(gè)例子,唯一的預(yù)防措施是將參數(shù)字符串轉(zhuǎn)換成整數(shù)類型。
到此這篇關(guān)于java中構(gòu)造器內(nèi)部調(diào)用構(gòu)造器實(shí)例詳解的文章就介紹到這了,更多相關(guān)java中關(guān)于構(gòu)造器內(nèi)部調(diào)用構(gòu)造器淺談內(nèi)容請(qǐng)搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. 讓chatgpt將html中的圖片轉(zhuǎn)為base64方法示例2. asp畫中畫廣告插入在每篇文章中的實(shí)現(xiàn)方法3. 使用純HTML的通用數(shù)據(jù)管理和服務(wù)4. ASP編碼必備的8條原則5. asp中Request.ServerVariables的參數(shù)集合6. WMLScript腳本程序設(shè)計(jì)第1/9頁7. CSS Hack大全-教你如何區(qū)分出IE6-IE10、FireFox、Chrome、Opera8. PHP反序列化漏洞實(shí)例深入解析9. ASP基礎(chǔ)知識(shí)Command對(duì)象講解10. PHP session反序列化漏洞深入探究
