Home > Software design >  Accessing the outer class when inheriting from it
Accessing the outer class when inheriting from it

Time:09-21

abstract class A {
    abstract inner class B : A() {
        init {
            // How can I access the outer class?
        }
    }
}

In this example, this refers to the class B, this@A refers to the parent class. How can I access the outer class?


Test case:

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()
}

CodePudding user response:

In your example, you created two objects - an instance of Parent, and an instance of Child.

Parent().Child()
   ^       ^
   |       |
   1       2

So there is really only two different things that you can access from the init block of B. 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).

"Accessing the outer class", which presumably you mean A, is not something you can do, because there is not even such an instance of A.

You can however, invoke A's implementations of methods/properties using [email protected] (note that it is not super@A. Read it as "super of B"). Perhaps this is what you intended on doing in the first place.

For example, changing A to the following:

abstract class A {

    override fun toString() = "A"

    abstract inner class B : A() {
        init {
            println("Should display 'Parent': ${[email protected]()}")
        }
    }
}

would print "A".

Note that this actually calls toString on the Child object, not the Parent object. You cannot do the same to the Parent object, because it is a different object. This init is creating the Child object, right?

In summary, this accesses some object that is in scope. super accesses a specific implementation of a method/property up the inheritance hierarchy.

  • Related