嵌套类
kotlin嵌套类声明如下:
class Outer {
... .. ...
class Nested {
... .. ...
}
}
嵌套类相当于外部类的一个成员,所以Outer
可以用.
符号来调用其嵌套类Nested
以及Nested
类里面的成员。
一个嵌套类例子:
class Person{
class Student{
var sayHi = "hello! Nice to meet you!"
fun sayHello() :String = sayHi
}
}
//使用下面的代码来调用嵌套类Student里面的方法
var helloString = Person.Student().sayHello()
println(helloString)
kotlin中的嵌套类相当于Java的静态内部类。在Java类中声明一个类,这个类就默认成为一个内部类。而Kotlin中的内部类必须使用inner
修饰符来声明。
内部类
kotlin内部类声明如下:
class Outer {
private val bar: Int = 1
inner class Inner {
fun foo() = bar
}
}
kotlin内部类可以访问外部类的成员,并且持有外部类的引用。
要访问外部类,我们使用this@label
,其中@label
指明this
的来源。
class Person{
val hiString = "hello! I'm a human"
inner class Student{
val sayHi = "hello! Nice to meet you!"
//this引用外部类
var outerHi = this@Person.hiString
//this自身引用
var innerHi1 = this@Student.sayHi
var innerHi2 = this.sayHi
}
}
//在其它地方调用内部类的代码
println(Person().Student().outerHi)