重载
public class Student {
private String name;
private int age;
public Student(String name, int age) {
this.name = name;
this.age = age;
}
public Student(String name) {
this.name = name;
}
}
参数设置默认值
Kotlin 主构造方法特点
指定名称就可以不按照参数顺序进行赋值,
通过设置 val 或是 var 修饰符
init 方法中也可以对构造方法中的参数进行赋值
class StudentKotlin(name: String = "xiaoming", var age: Int
) {
init{
age = 2
println("姓名 $name 年龄 $age)
}
}
//实例化 studentKotlin1
val studentKotlin1:StudentKotlin = StudentKotlin(name = "xiaohong",age = 1)
//实例化 studentKotlin2
val studentKotlin2:StudentKotlin = StudentKotlin(age = 2,name = "xiaohong")
fun main(args: Array<String>) {
//实例化 studentKotlin3 age 参数必传
val studentKotlin3: StudentKotlin = StudentKotlin(age = 5)
参数<生日>,通过已知<生日>直接获取到<年龄>。
public class Student {
private String name;
private int age;
private int birthday;
public Student(String name) {
this.name = name;
}
public Student(int birthday) {
this.age = getAgeByBirth(birthday);
}
//获取年龄
public int getAgeByBirth(int age) {
...
}
}
class Student(name: String = "xiaoming", age: Int = 0){
val age:Int = age
//从构造方法
constructor(birth:int):this(getAgeByBirth(birth))
//获取年龄
private fun getAgeByBirth(birth: Int): Int {
...
}
}
主从构造方法的特点
constructor 从构造方法主构造方法。
internal class StudentKotlin @inject constructor (name: String = "xiaoming", private var age: Int, private val birth: Int) {
init{
age = 2
println("姓名 $name 年龄 $age)
}
}一部分是其他构造方法的委托另一部分是由花括号包裹的代码执行顺序上会先执行委托的方法,然后再执行自身代码块的逻辑;如果一类存在主构造方法,那么每个从构造方法都要直接或间接地委托给它
public class MyView extends View {
public MyView(Context context) {
super(context);
}
public MyView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
}
public MyView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
public MyView(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
}class MyKotlinView : View {
//构造方法 A
constructor(context: Context?):this(context,null)
//构造方法 B
constructor(context: Context?, attrs: AttributeSet?) : this(context, null,0)
//构造方法 C
constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super(
context,
attrs,
defStyleAttr
) {
}
}
class MyKotlinView(context: Context?, attrs: AttributeSet?, defStyleAttr: Int, defStyleRes: Int) :
View(context, attrs, defStyleAttr, defStyleRes) {
constructor(context: Context?) : this(context, null)
constructor(context: Context?, attrs: AttributeSet?) : this(context, null, 0)
constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : this(
context,
null,
0,
0
)
}







