Kotlin Interfaces

In this tutorial you will learn about the Kotlin Interfaces and its application with practical example.

Kotlin Interfaces

The Kotlin Interface can contain method implementation and also abstract methods declaration, It is similar to Java 8.To use interface’s defined functionality we can implement it by a class. We can define interface in kotlin by keyword “interface”.

Table Of Contents

Define interface in Kotlin: As I told you that keyword “interface” is used to define interface in kotlin, See below code.

In above code “DemoInterface” an Interface, “demoVar” is an abstract property . infAbs () is an abstract method. The above interface also has a non-abstract method that is welcome().

 

Implementation of Interface: Let’s get understand that how we can implement interface by a class with the help of below simple code.

In above code DemoImp is a class which implements DemoInterface interface. The DemoImp class overrides abstract member demoVar and abstract method infAbs().

Example: Now let’s get know more about interface by it’s example, check below code.

Output: The output of this code will look like below image.

interface-1

Multiple Inheritance in Kotlin: Kotlin does not provide multiple inheritance but we can allow it using interface, we can implement one or more interface in single class. See below example.

Example:

Output: So output of this code will look like below image.

interface-2

Issue : Now suppose we have two interface with same non-abstract method name, suppose it is printMe() method. Now see what will happen. Check below code.

Output: It will give us error .

Solution : You can simply solve this problem by using below code.

Output: Now you can see in below image the output of above code.There is no error occurred.

interface-3

In this tutorial we have learn about the Kotlin Interfaces and its application with practical example. I hope you will like this tutorial.