简体   繁体   中英

kotlin, which function is called in the base class's init block

having a base class and Child derived from it:

open class Base(var data: String) {

    init {
        doInit()
    }
    open protected fun doInit() {
       data += " in Base doInit()"
    }
}

class Child(data: String): Base(data) {

    init {
        doInit()
    }
    override fun doInit() {

        data += super.doInit() + " in Child doInit()"
    }
}

val obj = Child("child")

in Child("child"), the Base's init{} is called. which doInit() the Base's init{} is supposed to call, from the Base's one or the Child's one?

If we define classes like this:

open class Base(var data: String) {

    init {
        doInit()
    }

    protected open fun doInit() {
        data += " in Base doInit()"
        println("in Base doInit()")
    }
}

class Child(data: String): Base(data) {

    override fun doInit() {
        data += " in Child doInit()"
        println("in Child doInit()")
    }
}

and create a child object:

val obj = Child("child")

we will see the output:

in Child doInit()

So when creating a child object and calling a function in base class that is overridden in child class, the child's function is called. That's called Polymorphism .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM