为了活动小家电-kotlin的构造函数(一)

109 阅读3分钟

携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第7天,点击查看活动详情

我想总结一下kotlin的构造函数。

首先,一般java中的构造函数className可以用下面的形式定义。

即使您有多个构造函数,Overloading也可以使用

public class Sample {

	private String name;
	private int age;
	private String birthday;

	public Sample(String name) {
		this.name = name;
	}

	public Sample(String name, int age) {
		this(name);
		this.age = age;
	}

	public Sample(String name, int age, String birthday) {
		this(name, age);
		this.birthday = birthday;
	}
}

Kotlin 构造函数

Kotlin 类中提到的constructor内容的总结。

  • 构造函数可以充当构造函数
  • 但是,它与java中描述的构造函数不同。

让我们使用 java 样式作为构造函数定义,如下所示。

class Sample constructor(val name: String) {

	constructor(name: String, age: Int): this(name)

	constructor(name: String, age: Int, birthday: String): this(name, age)
}

如果在 java 中按原样读取,则constructor(val name: String)this 存在,然后constructor(name: String, age: Int): this(name)仅将 name 传递给第一个构造函数并定义自身。

首先,如果我们把它换成更类似于 Kotlin 的方式,我们可以定义如下。

default使用构造函数定义听起来像 Kotlin。

class Sample(val name: String, val age: Int = 0, val birthday: String = "") {
	// 自己想做啥做啥吧
}

如果我们总结一下与java的区别

  • 通过声明默认变量可以一次定义3个构造函数

清理构造函数

如果您只是使用 kotlin,则default仅定义即可解决所有问题。

但是,并非所有这些都是特定于 kotlin 的,并且可以与 java 混合使用。

但是,我还没有检查那里定义的代码的结果是什么,以及它是否可以得到想要的结果。

您需要弄清楚 kotlin 构造函数的含义。

  • constructor可以像 (constructor) 一样使用,但不能像 java 那样初始化
  • init {}块有什么作用?

虽然 init 在这里看起来很重要,但让我们先再看一下 java。

public class Sample {
	private String name;
	private int age;

	public Sample(String name) {
		System.out.println("名字: " + name);
		this.name = name;
	}

	public Sample(String name, int age) {
		this(name);
		System.out.println("名字: " + name + ", 年龄: " + age);
		this.age = age;
	}
}

让我们检查一下上面代码的结果。 new Sample("帅哥")初始化第一个时

名字:帅哥

new Sample("帅哥", 18)初始化第二个时

名字:帅哥
名字:帅哥, 年龄: 18

让我们仔细看看kotlin代码

让我们定义并打印用 java 风格编写的 kotlin 的构造函数,如下所示。

class Sample {

	init {
		println("类的初始化")
	}

    constructor(name: String) {
        println("名字: $name")
    }

	constructor(name: String, age: Int): this(name) {
        println("名字: $name, 年龄: $age")
    }

	constructor(name: String, age: Int, birthday: String): this(name, age) {
        println("名字: $name, 年龄: $age 生日: $birthday")
    }
}

让我们通过构造函数运行上面的代码,看看结果如何。

初始化第一个Sample(“帅哥”)构造函数时

// 初始化块
类的初始化
// constructor(name: String)
名字: 帅哥

初始化第二个 Sample (“帅哥”, 18) 构造函数时

// 初始化块
类的初始化
// constructor(name: String, age: Int)
名字: 帅哥, 年龄: 18

初始化第三个Sample (“帅哥”, 18, “1111-01-01”) 构造函数时

// 初始化块
类的初始化
// constructor(name: String, age: Int, birthday: String)
名字: 帅哥, 年龄: 18,生日:1111-01-01

init?? 与构造函数有什么关系?

为了活动小家电,下一篇继续搞!