可能为一个类写了多个构造器,有时可能想在一个构造器里面调用另外一个构造器,为了减少代码的重复,可用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)