-
Notifications
You must be signed in to change notification settings - Fork 23
Accessing a variable of a sealed class
Devrath edited this page Aug 9, 2022
Β·
2 revisions
Just like normal class variables you can declare a variable in sealed class and access them
MainActivity.kt
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val monkeyObj = Monkey()
Log.d("Hello",monkeyObj.colorOfAnimal)
}
}
Animal.kt
sealed class Animal {
init {
Log.d("Hello","Initializing the animal class")
}
val colorOfAnimal = "White" // This is accessible because of open keyword
object Cat : Animal() // We can define a Object classes like this
data class Dog(val name: String) : Animal() // We can define data classes like this
}
object Camel : Animal()
class Monkey : Animal() {
init {
Log.d("Hello","Initializing the monkey class")
}
}
Output
2022-08-09 21:04:35.863 6982-6982/com.droid.democode D/Hello: Initializing the animal class
2022-08-09 21:04:35.863 6982-6982/com.droid.democode D/Hello: Initializing the monkey class
2022-08-09 21:04:35.863 6982-6982/com.droid.democode D/Hello: White