Kotlin的 companion object 修饰符

companion object (伴生对象)

1.1 调用测试
fun main(args : Array) {
    var mStudent = Student()
}
1.2 Student 对象

companion object (伴生对象):伴生对象在类中只能存在一个

package com.tct.freeze.kotlinstudydemo

class Student {

    // companion object (伴生对象):伴生对象在类中只能存在一个
    companion object {

        const val NAME = "TuanTuam"

        // 静态方法:等价于public static void initSettings()
        fun initSettings() {
            println("initSettings $NAME")
        }
    }

    var mName =  NAME

    // 静态方法:等价于public static void init()
    init {
        initSettings()

        println("Student name is $mName")
    }
}

运行结果

initSettings TuanTuam
Student name is TuanTuam

Process finished with exit code 0

你可能感兴趣的:(Kotlin,companion,修饰符,kotlin,static)