-
Notifications
You must be signed in to change notification settings - Fork 22
Accessing a function in sealed class
Devrath edited this page Aug 9, 2022
·
2 revisions
- Just like a regular class, we can also have functions in a sealed class, Here is the demo of it.
- In the demo we even show-case that variable can be modified
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--->")
monkeyObj.printColorOfAnimal()
Log.d("Hello","Animal number: -> "+monkeyObj.animalNumber)
monkeyObj.animalNumber++
Log.d("Hello","Animal number: -> "+monkeyObj.animalNumber)
Log.d("Hello","<----END--->")
}
}
Animal.kt
sealed class Animal {
init {
Log.d("Hello","Initializing the animal class")
}
private val colorOfAnimal = "White"
var animalNumber = 0
fun printColorOfAnimal() {
Log.d("Hello", "Animal color :-> $colorOfAnimal")
}
}
object Camel : Animal()
class Monkey : Animal() {
init {
Log.d("Hello","Initializing the monkey class")
}
}
Output
2022-08-09 22:20:28.519 8290-8290/com.droid.democode D/Hello: Initializing the animal class
2022-08-09 22:20:28.519 8290-8290/com.droid.democode D/Hello: Initializing the monkey class
2022-08-09 22:20:28.519 8290-8290/com.droid.democode D/Hello: <----START--->
2022-08-09 22:20:28.519 8290-8290/com.droid.democode D/Hello: Animal color :-> White
2022-08-09 22:20:28.519 8290-8290/com.droid.democode D/Hello: Animal number: -> 0
2022-08-09 22:20:28.519 8290-8290/com.droid.democode D/Hello: Animal number: -> 1
2022-08-09 22:20:28.519 8290-8290/com.droid.democode D/Hello: <----END--->