java构造器调用构造器_java中构造器内部调用构造器实例详解
可能為一個類寫了多個構(gòu)造器,有時可能想在一個構(gòu)造器里面調(diào)用另外一個構(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這個關(guān)鍵字。
內(nèi)容補(bǔ)充:
構(gòu)造函數(shù)的作用
這個示例項(xiàng)目中的 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ù)類型。
原文鏈接:https://www.cnblogs.com/xpeanut/p/12863070.html
(資源庫 www.zyku.net)
總結(jié)
以上是生活随笔為你收集整理的java构造器调用构造器_java中构造器内部调用构造器实例详解的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: java 原理图_Java中比较重要的原
- 下一篇: java 漏洞挖掘_Apache Tik