Kotlin Interfaces

19. Kotlin Interfaces 19.1 Interfaces 19.2 Implementing Interface 19.3 Implementing Multiple Interfaces


Interfaces

Kotlin Interface is declared with the keyword 'interface'. Within the interface, the declared method has optional body. A class can implement an interface using the 'implements' keyword. Kotlin interface contains the declarations of abstract methods as well as method implementations. The interfaces are open by default, there is no need to write open keyword.

Interface Example

interface school {
	val students: Long
	
	fun attendance() {
		println("Total present students")
	}
}

Implementing Interface

In the below code, we have created an interface name 'school', this contains a function attendance. The KG class implements the school interface and override the method and property.

fun main(args : Array<String>)  { 
	val x = KG()
    x.attendance()
}
interface school {
    val students: Int

    fun attendance() {
        println("Total present students")
    }
}
class KG : school {
    override val students: Int = 60
    override fun attendance(){
        println("Total present students ${students}.")
    }
}
Output of the above code
Total present students 60.


Implementing Multiple Interfaces

A class can implement multiple interfaces and each interface are separated by comma.

fun main(args : Array<String>)  { 
    val x = C()
    x.present()
    x.absent()
}
interface A {
    fun present():String
}
interface B {
    fun absent():String
}

class C : A, B {
    override fun present() = "Get total present students."
    override fun absent() = "Get total absent students."
}   
Output of the above code
Get total present students.
Get total absent students.

In the above example, we have created two interfaces A and B and a class C. The class C implements both interfaces and override its functions.







Read more articles


General Knowledge



Learn Popular Language