Skip to content

Latest commit

 

History

History
122 lines (82 loc) · 2.53 KB

File metadata and controls

122 lines (82 loc) · 2.53 KB

Kotlin 嵌套和内部类

原文: https://www.programiz.com/kotlin-programming/inner-nested-class

在本文中,您将借助示例学习使用嵌套类和内部类。

Kotlin 嵌套类

与 Java 类似,Kotlin 允许您在另一个称为嵌套类的类中定义一个类。

class Outer {
    ... .. ...
    class Nested {
        ... .. ...
    }
}

由于Nested类是其封闭类Outer的成员,因此可以使用.表示法访问Nested类及其成员。


示例:Kotlin 嵌套类

class Outer {

    val a = "Outside Nested class."

    class Nested {
        val b = "Inside Nested class."
        fun callMe() = "Function call from inside Nested class."
    }
}

fun main(args: Array<String>) {
    // accessing member of Nested class
    println(Outer.Nested().b)

    // creating object of Nested class
    val nested = Outer.Nested()
    println(nested.callMe())
}

运行该程序时,输出为:

Inside Nested class.
Function call from inside Nested class.

适用于 Java 用户

Kotlin 中的嵌套类类似于 Java 中的静态嵌套类。

在 Java 中,当您在另一个类中声明一个类时,默认情况下它将成为一个内部类。 但是在 Kotlin 中,您需要使用inner修饰符来创建一个内部类,我们将在下面讨论。


Kotlin 内部类

Kotlin 中的嵌套类无法访问外部类实例。 例如,

class Outer {
    val foo = "Outside Nested class."

    class Nested {
        // Error! cannot access member of outer class.
        fun callMe() = foo
    }
}

fun main(args: Array<String>) {

    val outer = Outer()
    println(outer.Nested().callMe())
}

上面的代码无法编译,因为我们尝试从Nested类内部访问Outer类的foo属性。

为了解决此问题,您需要使用inner标记嵌套的类以创建内部类。 内部类带有对外部类的引用,并且可以访问外部类成员。


示例:Kotlin 内部类

class Outer {

    val a = "Outside Nested class."

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

fun main(args: Array<String>) {

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

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

运行该程序时,输出为:

Using outer object: Outside Nested class.
Using inner object: Outside Nested class.

推荐阅读匿名内部类