java构造器调用构造器_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);
}
代碼的主要部分提供運行應用程序時提供的任何參數。這的確會是一個復雜的應用程序,你需要仔細解析參數并檢查意外結果,但對于這個例子,唯一的預防措施是將參數字符串轉換成整數類型。
原文鏈接:https://www.cnblogs.com/xpeanut/p/12863070.html
(資源庫 www.zyku.net)
總結
以上是生活随笔為你收集整理的java构造器调用构造器_java中构造器内部调用构造器实例详解的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: java 原理图_Java中比较重要的原
- 下一篇: java 漏洞挖掘_Apache Tik