类和方法
# 1. 构造方法
https://zhuanlan.zhihu.com/p/79087128
Java Bean类
public class Person {
private String name;
private int age;
private Object feature;
public Person() { }
public Person(String name, int age, Object feature) {
this.name = name;
this.age = age;
this.feature = feature;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Object getFeature() {
return feature;
}
public void setFeature(Object feature) {
this.feature = feature;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
转换为Kotlin
package top.iqqcode.loop
class Person {
var name: String? = null
var age = 0
var feature: Any? = null
constructor() { }
constructor(name: String?, age: Int, feature: Any?) {
this.name = name
this.age = age
this.feature = feature
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
2
3
4
5
6
7
8
9
10
11
12
13
14
15
如果只有一个构造方法,可简化为(去掉constructor和括号)
class Person(var name: String, var age: Int, var feature: Any)
1
# 2. 代码块等价
- 如果在该构造函数中无其他操作,则继续简化为
class Person(var name: String, var age: Int, var feature: Any)
1
- 如果有其他操作,则写在init中
class Person(var name: String, var age: Int, var feature: Any) {
init {
println("Hello $name")
}
}
1
2
3
4
5
2
3
4
5
编辑 (opens new window)
上次更新: 2022/06/04, 11:36:35