Skip to content

Role of abstract variable in sealed class

Devrath edited this page Aug 9, 2022 · 2 revisions
  • If we add a variable as abstract in the sealed class, it will force us not to initialize the variable and force us to specify the variable type.
  • Now any classes that inherit the sealed class have to over-ride the variable and initialize the variable.

MainActivity.kt

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val monkeyObj = Monkey()
        Log.d("Hello","<----START--->")
        Log.d("Hello","Animal number: -> "+monkeyObj.colorOfAnimal)
        Log.d("Hello","<----END--->")

    }
}

Animal.kt

sealed class Animal {
    init {
        Log.d("Hello","Initializing the animal class")
    }

    abstract val colorOfAnimal : String

}
object Camel : Animal() {
    override val colorOfAnimal: String
        get() = "Yellow"
}

class Monkey : Animal() {
     init {
         Log.d("Hello","Initializing the monkey class")
     }

    override val colorOfAnimal: String
        get() = "Red"
}

Output

2022-08-09 22:36:10.794 8482-8482/com.droid.democode D/Hello: Initializing the animal class
2022-08-09 22:36:10.794 8482-8482/com.droid.democode D/Hello: Initializing the monkey class
2022-08-09 22:36:10.794 8482-8482/com.droid.democode D/Hello: <----START--->
2022-08-09 22:36:10.795 8482-8482/com.droid.democode D/Hello: Animal number: -> Red
2022-08-09 22:36:10.795 8482-8482/com.droid.democode D/Hello: <----END--->
Clone this wiki locally