[英]Accessing the outer class when inheriting from it
abstract class A {
abstract inner class B : A() {
init {
// How can I access the outer class?
}
}
}
在此示例中, this
指的是 class B
, this@A
指的是父 class。 如何訪問外部 class?
測試用例:
abstract class A {
abstract inner class B : A() {
init {
println("Should display 'Parent': $this") // replace 'this' by something else?
}
}
}
class Parent : A() {
override fun toString() = "Parent"
inner class Child() : B() {
override fun toString() = "Child"
}
}
fun main() {
Parent().Child()
}
在您的示例中,您創建了兩個對象 - 一個Parent
實例和一個Child
實例。
Parent().Child()
^ ^
| |
1 2
因此,您實際上只能從B
的init
塊訪問兩種不同的東西。 You can either access the Parent
object using this@A
, which is the object associated with the Child
object, or the Child
object itself using this
(or redundantly this@B
).
“訪問外部類”,大概是您的意思A
,不是您可以做的事情,因為甚至沒有這樣的A
實例。
但是,您可以使用super@B.xxx
調用A
的方法/屬性的實現(請注意,它不是super@A
。將其讀作“ B
的超級”)。 也許這就是您最初打算做的事情。
例如,將A
更改為以下內容:
abstract class A {
override fun toString() = "A"
abstract inner class B : A() {
init {
println("Should display 'Parent': ${super@B.toString()}")
}
}
}
將打印“A”。
請注意,這實際上調用Child
object 上的toString
,而不是Parent
object。 您不能對Parent
object 執行相同操作,因為它是不同的 object。 這個init
正在創建Child
object,對嗎?
總之, this
會訪問 scope 中的一些 object。 super
訪問 inheritance 層次結構中方法/屬性的特定實現。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.