kotlin構造方法

說明: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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章