簡體   English   中英

繼承時訪問外部 class

[英]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 Bthis@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

因此,您實際上只能從Binit塊訪問兩種不同的東西。 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM