Kotlin – Interfaces

Interface is a collection of abstract methods. Abstract method is a method that is declared but does not contain any implementation. In Kotlin interfaces can contain abstract methods as well as non-abstract methods, implemented methods.

Interface declaration

interface telephone{
    fun call()
    fun answer(telephoneNumber: Int) {
        println("Answering $telephoneNumber")
    }
}

Implementing interface

class Smartphone: telephone{
    
}

interface telephone{
    fun call()
    fun answer(telephoneNumber: Int) {
        println("Answering $telephoneNumber")
    }
}
An interface is a collection of abstract methods., <span>Kotlin – Interfaces</span>, KandZ

The class Smartphone inherits telephone. But there is an error, see the red line. The error says:

Class ‘Smartphone’ is not abstract and does not implement abstract member public abstract fun call(): Unit defined in kronos.telephone

That means you have to implement the method call(). Place your cursor on the error and press alt + Enter and select Implement methods

An interface is a collection of abstract methods., <span>Kotlin – Interfaces</span>, KandZ

You will see a pop-up window with the member you can implement. Select the one you want to implement and click OK

An interface is a collection of abstract methods., <span>Kotlin – Interfaces</span>, KandZ

function call added with override at the start. Now you can implement it.

An interface is a collection of abstract methods., <span>Kotlin – Interfaces</span>, KandZ
class Smartphone: telephone{
    override fun call() {
        println("I am calling ")
    }

}

interface telephone{
    fun call()
    fun answer(telephoneNumber: Int) {
        println("I am calling $telephoneNumber")
    }
}

If an interface has an implemented function, then you can call the function of its supertype with the keyword super. How you can do that:

super<Name>.functionName()
class Smartphone: telephone{
    override fun call() {
        println("I am calling ")
    }

    override fun answer(telephoneNumber: Int) {
        super<telephone>.answer(telephoneNumber)
    }

}

interface telephone{
    fun call()
    fun answer(telephoneNumber: Int) {
        println("I am calling $telephoneNumber")
    }
}

You can skip <telephone> when the class inherits from one interface, or more than one but they do not implement the same function.

override fun answer(telephoneNumber: Int) {
        super.answer(telephoneNumber)
    }

Read more here.

65380cookie-checkKotlin – InterfacesKotlin – Interfaces

Related posts

2 Thoughts to “Kotlin – Interfaces

  1. […] interface telephone{ fun Read More […]

Comments are closed.