The enum class and interfaces

Just like normal classes, the enum class is also able to implement interfaces. In this case, each member in the enum class will be responsible for providing the function body of each function signature that is mentioned in the interface.

Let's create an interface, printable, with one function, show(). Create an enum class, NEWS, and implement the printable interface:

interface printable {
fun show()
}

enum class NEWS : printable {

NORTH {
override fun show() {
println("Can you explain to me what summer is")
}
}, EAST {
override fun show() {
println("Can you explain to me what cold is")
}
}, WEST {
override fun show() {
println("I know what winter and summer are")
}
}, SOUTH {
override fun show() {
println("Oh .. its humid here...")
}
}
}

As we can see, each enum member has implemented the show override function.

Call the enum class in the main function and see the output:

 fun main(args: Array<String>) {

var item = NEWS.valueOf("EAST")
item.show()

item = NEWS.valueOf("SOUTH")
item.show()
}

Each item of the enum class displays the appropriate message, as we can see in the following output:

Can you explain to me what cold is
Oh .. its humid here...
..................Content has been hidden....................

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