The object class with inheritance and interfaces

Like normal classes, the object class can also make the most of the benefits of inheritance. We can create a normal parent class that can be extended by the object class. In the following example, we have a class called Parent with one callMySingleton function. We also have one MySingleton object class, which extends the parent class. The MySingleton class overrides the callMySingleton() function:

open class Parent {
open fun callMySingleton(){
println("Parent class is called")
}
}

object MySingleton : Parent() {
override fun callMySingleton(){
super.callMySingleton()
println("my Singleton class is called")
}
}

In the main function, we use a single instance of the object class, call the member function, and verify the output. The object class calls the function of the parent class with the super keyword and then prints its own output on the screen:

fun main(args: Array<String>) {
MySingleton.callMySingleton()
}

The output of this is as follows:

Parent class is called
my Singleton class is called

The object class is also able to implement interfaces. The following example shows the MyButton class providing the implementation of a function that is declared in buttonInterface:

interface buttonInterface {
fun clickMe()
}

object MyButton : buttonInterface {
var count = 0
override fun clickMe() {
println("I have been clicked ${++count} times")
}
}

fun main(args: Array<String>) {
MyButton.clickMe()
MySingleton.callMySingleton()
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
13.59.209.131