说明:kotlin构造方法和java稍有不同,许多初学者并不知道怎么实现kotlin构造方法
主函数:
fun main(){
val bird = Bird5(100.5,78,"yellow")
bird.printSex();
println("main: ${bird.age},${bird.weight},${bird.color}")
}
构造方法类:kotlin可以直接在类接变量,然后在init里面赋值,自定义方法就直接写就可以了,然后在主函数里面调用,
class Bird5 (weight : Double = 0.00,age : Int = 1,color : String = "blue"){
val weight : Double
val age : Int
val color : String
var sex : String = ""
//构造方法
init {
this.weight = weight;
this.age = age*2
println("${this.weight}")
println("${this.age}")
}
init{
this.color = color;
println("${this.color}")
}
//自定义方法
fun printSex(){
this.sex = if (this.color == "yellow") "male" else "female"
println("${this.sex}")
}
}
运行结果:
100.5
156
yellow
male
main: 156,100.5,yellow
Process finished with exit code 0
end