Kotlin – Interface

Kotlin – Interface

In this section, we will find out about the interface in Kotlin. In Kotlin, the interface works precisely like Java 8, which means they can contain technique execution just as conceptual strategies assertion. An interface can be actualized by a class so as to utilize its characterized usefulness. we will get familiar with it. The catchphrase “interface” is utilized to characterize an interface in Kotlin as appeared in the accompanying bit of code.

interface ExampleInterface {
var myVar: String // abstract property
fun absMethod() // abstract method
fun sayHello() = "Hello there" // method with default implementation
}

In the above model, we have made one interface named as “ExampleInterface” and inside that we have two or three conceptual properties and techniques all together. Take a gander at the capacity named “sayHello()”, which is an actualized strategy.

In the accompanying model, we will actualize the above interface in a class.

interface ExampleInterface {
var myVar: Int // abstract property
fun absMethod():String // abstract method
fun hello() {
println("Hello there, Welcome to softwarelogy.com!")
}
}
class InterfaceImp : ExampleInterface {
override var myVar: Int = 11
override fun absMethod() = "Happy Learning "
}
fun main(args: Array<String>) {
val obj = InterfaceImp()
println("My Variable Value is = ${obj.myVar}")
print("Calling hello(): ")
obj.hello()
print("Message from the Website-- ")
println(obj.absMethod())
}

The above bit of code will yield the accompanying yield in the program .

My Variable Value is = 11

Calling hello(): Hello there, Welcome to softwarelogy.com!

Message from the Website– Happly Learning

As referenced before, Kotlin doesn’t bolster different legacies, be that as it may, something very similar can be accomplished by executing multiple interfaces at once.

In the accompanying model, we will make two interfaces and later we will execute both the interfaces into a class.

interface A {
fun printMe() {
println(" method of interface A")
}
}
interface B {
fun printMeToo() {
println("I am another Method from interface B")
}
}
// implements two interfaces A and B
class multipleInterfaceExample: A, B
fun main(args: Array<String>) {
val obj = multipleInterfaceExample()
obj.printMe()
obj.printMeToo()
}

In the above model, we have made two example interfaces A, B and in the class named “multipleInterfaceExample” we have executed two interfaces announced before. The above bit of code will yield the accompanying yield in the program.

method of interface A

I am another Method from interface B

Leave a Reply

Your email address will not be published. Required fields are marked *