嵌套和内部类


nested class 更像是java中的静态内部类,但是不能访问内部成员,

inner class 更像是java的内部类,需要关键字inner

fun BaseMain() {

    val inner = Outer().Inner()
    println("Using inner object: ${inner.callMe()}")

    println("Using the nested Object:${Outer.Nested().call()}")

}


class Outer {

    val a = "Outside Nested class."

    inner class Inner {
        //
        fun callMe() = a
    }

    class Nested {
        fun call() {
            println("This can not call the Outer class's variable.")
        }
    }
}

匿名内部类

  • 关键字object
  • 使用,主要是使用在实例化接口上
fun BaseMain() {
    var ani = object : IAnimal {
        override fun gogo() {
            println("If you are a animal,you will take it easy .")
        }
    }
    ani.gogo()

}

interface IAnimal {
    fun gogo() {
        println("This is test for you.")
    }
}

results matching ""

    No results matching ""