Home > Software design >  How to initialize a variable of an abstract class from a child class
How to initialize a variable of an abstract class from a child class

Time:07-30

I have an abstract class:

inner abstract class Base {        
        fun Buscar(): Int {
            // Do something with a object called Q
        }
    }

And two secondary class that I need to initialize Q with certain class

    inner class BFS(): Base() {
        constructor(): this() {
            Q = Cola()
        }
            
    }

    inner class DFS(): Base() {
        constructor(): this() {
            Q = Pila()
        }        
    }

How can I do that?

--- EDIT --- Pila() and Cola() are classes from an abstract class called Secuencia:

abstract class Secuencia<T> { ... }
public class Pila<T> : Secuencia<T>() { ... }
public class Cola<T> : Secuencia<T>() { ... }

CodePudding user response:

You just need to make Q abstract and initialise it in your class, e.g.

sealed class Algo(val message: String)
class Cola : Algo("cola")
class Pila : Algo("pila")

abstract class Base {
    // all concrete classes need to define a value for 'q'
    abstract val q: Algo
    
    fun buscar(): Int {
        // you can reference q here since a concrete class will have initialised it
        println(q.message)
        return 1
    }

}

class BFS(): Base() {
    // since q is abstract it needs to be overridden in a concrete class
    override val q = Cola()
}

class DFS(): Base() {
    override val q = Pila()       
}

fun main() {
    BFS().buscar()
    DFS().buscar()
}

>> cola
>> pila
  • Related