java中構造器內部調用構造器實例詳解
可能為一個類寫了多個構造器,有時可能想在一個構造器里面調用另外一個構造器,為了減少代碼的重復,可用this關鍵字做到這一點。
public class Flower { private String string; private int age; public Flower() { // 先調用public Flower(String string, int age) this('leon', 120); // 先調用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); }}
其實可以從結果看見,這其實可普通的函數調用沒什么區別,只不過是用了this這個關鍵字。
內容補充:
構造函數的作用
這個示例項目中的 DiceRoller 類表示一個虛擬骰子工廠:當它被調用時,它創建一個虛擬骰子,然后進行“滾動”。然而,通過編寫一個自定義構造器,你可以讓擲骰子的應用程序詢問你希望模擬哪種類型的骰子。
大部分代碼都是一樣的,除了構造器接受一個表示面數的數字參數。這個數字還不存在,但稍后將創建它。
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; }
模擬滾動的函數保持不變:
public void Roller() { roll = rand.nextInt(dice); roll += 1; System.out.println (roll);}
代碼的主要部分提供運行應用程序時提供的任何參數。這的確會是一個復雜的應用程序,你需要仔細解析參數并檢查意外結果,但對于這個例子,唯一的預防措施是將參數字符串轉換成整數類型。
到此這篇關于java中構造器內部調用構造器實例詳解的文章就介紹到這了,更多相關java中關于構造器內部調用構造器淺談內容請搜索好吧啦網以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持好吧啦網!
相關文章:
