您的位置:首页 > 编程语言 > Java开发

java中构造器内部调用构造器实例详解

2020-05-11 04:04 741 查看

可能为一个类写了多个构造器,有时可能想在一个构造器里面调用另外一个构造器,为了减少代码的重复,可用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中关于构造器内部调用构造器浅谈内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java 构造器