Implement Interface In Kotlin With Example

Greetings!
We have recently published 100+ articles on android tutorials with kotlin and java. If you need, you may visit Android Tutorial for beginners page. You can also check Kotlin Tutorial for beginners. Also, if you are interested in content writing, you can mail us at tutorialwing@gmail.com.
An interface is nothing more than a contract. It contains definitions for a set of related functionalities. The implementer of the interface has to attach to the interface, the contract, and implement the required methods. Just like Java 8, an interface in kotlin contains the declarations of abstract methods as well as method implementations. Unlike abstract classes, an interface cannot contain state. However, it can contain properties that needs to be abstract or to provide accessor implementations.

In this article, we will go through concepts of kotlin interface with examples. We will see how to define, implement interface in kotlin, different features of kotlin interface, multiple interface in same class, how does interface works in kotlin etc. Then, we will see real life example of interface in kotlin.

1. Define interface in kotlin

Interface can be defined using keyword – interface. For example,

interface MyInterface {
    val name: String
}

Here, we have defined an interface MyInterface using keyword interface. In this interface, a variable name has been declared.

We can also declare an abstract method inside interface. For example,

interface MyInterface {
   val name: String  //abstract variable
   fun foo()  //abstract method
}

In MyInterface, an abstract variable name and method foo() has been declared.

You can also define non-abstract method in interface in kotlin. For example,

interface MyInterface {
   val name: String  //abstract variable
   fun sayHello() {
         print("Hello")
    }
}

Here, we have defined a method sayHello in interface MyInterface.

Till now, we have seen how to define interface in kotlin. Now, we will see how to implement interface in kotlin.




2. Implement Interface in kotlin

A class or object can implement interface in Kotlin as below –

interface MyInterface {
   val name: String  //abstract variable
}

class MyClass: MyInterface {
   override val name: String
}

Here, a class MyClass implements an interface MyInterface. Notice that class also overrides abstract member as well.

Let’s see other examples as well –

interface MyInterface {
   val name: String  //abstract variable
   fun foo() 
}

class MyClass: MyInterface {
   override val name: String
   override fun foo() {
      print("hello")
   }
}

Here, class MyClass also overrides abstract method, foo(), declared in interface MyInterface.

We have just seen how to implement interface in kotlin. Now, can you imagine what if there is any non-abtract method present in interface ? How to implement interfaces with default implementation in kotlin ?

3. Interfaces with default implementation in Kotlin

  • First create an interface named MyInterface
interface MyInterface
{
   fun withImplement()
   {
        println("Hello this is my default interface")
    }
}
class InterfaceImplement: MyInterface
{
 // No need to reimplement here
}
  • Inside our main method we are creating an instance of the class name InterfaceImplement for calling the method
 
fun main(Args:Array<String>)
{
  var inst = InterfaceImplement() 
  inst.withImplement()
} 

*Finally we get the output as: Hello this is my default interface

Properties of default implementation

  • The major property of Default Implementation is working on, for getters and setters
 
interface MyInterface
{
  val hello
  get() = "hello"
}
class Interf: MyInterface
{
  // Let this field be empty
}
fun main(Args:Array<String>)
{
  var inst = Interf()
  print(inst.hello)
}
  • But interface accessors implementation can’t use backing field
 
interface MyInterface
{
 var hello: Int
 get() = field
 set(value)
 {
    field = value
 }
}

The above code will not compile and will give you an error i.e. To have more idea about this code error you can try it out on your own computer and can have a clear idea about it.

You can try running above code on – Official Kotlin Playground




4. How Interface Works in Kotlin ?

Let’s have a complete program to see how interface works in kotlin –

interface MyInterface {
    val name: String
    fun foo() : String
    fun printHello() {
        println("printHello() method called")
    }
}
class InterfaceImp : MyInterface {
    override val name: String = "Rajeev"
    override fun foo() = "foo() method called"
}
fun main(args: Array<String>) {
    val instance = InterfaceImp()
    println("Name = ${instance.name}")
    println("Calling printHello() Method - ")
    instance.printHello()
    println("Calling foo() Method - ")
    println(instance.foo())
}

Let’s get it one by one –

  1. MyInterface – We have defined an interface that contains –
    1. an abstract property  name.
    2. an abstract method foo()
    3. a method with default implementation printHello()
  2. InterfaceImp – This is a class that implements interface MyInterface. Notice that InterfaceImp class also overrides  abstract property and method. But, it does not overrides method with default implementation. So, InterfaceImp overrides name and foo().
  3. Now, we have used this class in main method. We have created an instance of InterfaceImp class. Then, we have called methods and properties present inside this class.

 

When you run above program, Output will be –

Name = Rajeev
Calling printHello() Method - 
printHello() method called
Calling foo() Method - 
foo() method called

5. Implement Multiple Interfaces in Kotlin

Till now, we have seen how to implement an interface in kotlin. Now, what if you want to implement multiple interfaces in same class ? How can you achieve it ?

You can use this feature to implement multiple inheritance in kotlin.

Syntax to implement multiple interfaces in kotlin –


class ClassName: InterfaceNameA, InterfaceNameB {

// Overrides Methods present in different interfaces...

}

Let’s see an example –


interface A {
   fun methodA()
}

interface B {
   fun methodB()
}

class MultipleInterface: A, B {
   override fun methodA() {
      print("Method A Overrided!")
   }
   override fun methodB() {
      print("Method B Overrided!")
   }
}

In this example, We have defined two interfaces A and B. Then, we have defined a class MultipleInterface that implements interfaces A and B. Note that methodA() and methodB() has also been overridden in class MultipleInterface. This is how you implements multiple interfaces in kotlin.

What do you think what should be output if you run below program –


interface A {
    fun methodA()
}

interface B {
    fun methodB()
}

class MultipleInterface: A, B {
    override fun methodA() {
        println("Method A Overriden!")
    }
    override fun methodB() {
        print("Method B Overriden!")
    }
}

fun main(args: Array<String>) { 
 	   
    val obj = MultipleInterface()
    obj.methodA()
    obj.methodB()   
}

Output will be –

Method A Overriden!
Method B Overriden!



Resolving Overriding Conflicts in Multiple Interface in Kotlin

Now, you know how to implement multiple interfaces in kotlin.

Great!

I have a question for you now. What if two interfaces have non-abstract method with same name. Let’s name this method printHello().

Let’s consider below code

interface A {
    fun printHello() {
        println("Hello from A")
    }
}

interface B {
    fun printHello() {
        println("Hello from B")
    }
}

class MultipleInterface: A, B

fun main(args: Array<String>) { 
	val obj = MultipleInterface()
    obj.printHello()
}

Oops!

You get an error when you run the program –

// Error you get  - 
Class 'MultipleInterface' must override public open fun printHello(): Unit defined in A because it inherits multiple interface methods of it

Now what ?

How do you solve the issue?

In kotlin, you can resolve the conflict by providing own implementation of method in class that implements these interfaces. So, you can solve the conflict as below –

class MultipleInterface: A, B {
    override fun printHello() {
        super<A>.printHello()
        super<B>.printHello()
    }
}

Here,

super<A>.printHello() calls method from interface A.
super<B>.printHello() calls method from interface B.

So, the final code after resolving conflict for multiple interface in kotlin is –

interface A {
    fun printHello() {
        println("Hello from A")
    }
}

interface B {
    fun printHello() {
        println("Hello from B")
    }
}

class MultipleInterface: A, B {
    override fun printHello() {
        super<A>.printHello()
        super<B>.printHello()
    }
}

fun main(args: Array<String>) { 
    val obj = MultipleInterface()
    obj.printHello()
}

Now, when you run the program, you get output as –

Hello from A
Hello from B

Now, we have a question for you –

Question 1

Can you guess output of below program ?

interface A {
    fun nothingImplemented()

    fun implementOnlyInA() {
        println("Only a")
    }

    fun implementInBoth() {
        println("Both A")
    }

    fun implementedInOne() {
        println("Implemented in A")
    }
}

interface B {
    fun implementedInBoth() {
        println("Both B")
    }
    fun implementedInOne() // not defined 
}

class MultipleInterface: A, B {
    override fun nothingImplemented() {
        println("normal implementation")
    }
    override fun implementedInBoth() {
        super.implementInBoth()
        super.implementedInBoth()
    }
    override fun implementedInOne() {
        super.implementedInOne()
        println("Implemented in one for Class B")
    }
}

fun main(args: Array<String>) { 
 	   
    val obj = MultipleInterface()
    obj.nothingImplemented()
    obj.implementOnlyInA()    
    obj.implementedInBoth()
    obj.implementedInOne()    
}

Output will be –

6. Inheritance in Interface in Kotlin

Have you ever come across a situation where you want to define a class that borrows some feature from other class ?

Same applies with interface in kotlin. What if you want to define an interface that borrows some features from other interface?

This is called interface inheritance in kotlin. Here, you define an interface and borrows some features from other interface.

For example,

interface Named {
    val name: String
}

interface Person : Named {
    val firstName: String
    val lastName: String
    
    override val name: String get() = "Your name is $firstName $lastName"
}

data class Employee(
    // implementing 'name' is not required
    override val firstName: String,
    override val lastName: String
) : Person


fun main(Args:Array<String>)
{
  var obj = Employee("Rajeev", "Kumar")
  print(obj.name)
}

Here, interface Person inherits another interface Named. This way it gets access to property name that shows full name combining firstName and lastName.

When you run above program, you get output –

Your name is Rajeev Kumar



7. Real Life Example of Interface in kotlin

Till now we have seen what is interface , syntax to declare and define interface in kotlin, how to perform interface inheritance in kotlin etc. Now, we will see how to apply it in real life.

We will take an example and apply interface using kotlin in it.

Before you move ahead into details, Can you think of a real life scenario where you can apply interface?

Did you get an example ?

YES / NO ?

If YES, Good Job!

If NO, Do not worry! We have an example for you.

Now, Those, who got an example, can you think whether you can apply concepts like multiple interface, interface inheritance using kotlin etc. in your example ?

If YES, Good Job! That’s it for you in this post. Now, you can check out our other topics in kotlin.

If NO, Do not worry! We will go ahead together and see how we can apply such concepts.

In our daily life, we see so many vehicles Bus, Truck, Bike Car etc. We are going to apply interface in it.

Please note that this example covers only basic features of Vehicle so that everyone can understand how concepts of interface can be applied in real life.

Every vehicle has some features – it accelerates, stops, take left turn, take right turn etc. So, we will declare such features in interface. Then, vehicles that need such feature will implement that interface.

Thus, our work is to define each feature in separate interface.

So, we are going define an interface Vehicle that contains features accelerate and stop.

interface Vehicle
{
  fun accelerate()
  fun stop()
}

Here, interface Vehicle has features such as accelerate and stop. So, Vehicle that needs such feature will implements this interface.

Red Alert

You can not instantiate an interface. Actually, this is correct – How can you get an object of feature?

So, running below code will give you an error –

val obj = new Vehicle()

Now, what if your vehicle changes it’s direction (either left or right)?

So, we will define another interface VehicleWithDirection that contains such features. But, you would not like to define other features such as accelerate and stop because you have already defined an interface Vehicle for such featurea. Instead you would like to re-use it. Fortunately, you can apply inheritance in interface in kotlin. So, our interface will be like –

enum class Direction {
   Left, Right
}

interface VehicleWithDirection: Vehicle
{
  fun turn(direction: Direction)
}

Here, enum class is just to be used as Direction. Do n’t worry about it. Just consider it as some value that indicates left direction or right direction.

Can you notice inheritance in interface using Kotlin here ?

YES!

You got it.

interface VehicleWithDirection inherits another interface Vehicle. Thus, VehicleWithDirection also has features such accelerate() and stop(). So, If your vehicle accelerates, stops, or takes left or right turns, then, you can use VehicleWithDirection instead of using Vehicle interface.

That’s it. Now, you can use it in your class if you want to provide direction.

What if you want to provide a default direction in your interface? You can provide a default value in method in interface in kotlin. You can do it as below –

enum class Direction {
   Left, Right
}
interface VehicleWithDirection: Vehicle
{
  fun turn(direction: Direction = Direction.Left)
}

Now, if you want to implement interface VehicleWithDirection, then, a default direction Left will be set if you do not provide any value while using this interface in your class.

Vehicle also has wheels. Some vehicle has 2 number of wheels, some has 3 or 4 or more. Some has larger wheels while some has small wheels. so, we will define another interface WheelerType that defines wheels in vehicle.

interface WheelerType
{
  val numOfWheels: Int
  val wheelSize: Double
}

interface WheelerType describes how many number of wheels a vehicle has, what are the size of wheels etc. So, if you need such features to define in your class, you can use this interface.

Now, we will define a class Bike that uses such interfaces to define it’s features.

class Bike: Vehicle, WheelerType {
    var moveForward = false
    var stop = false
    override val numOfWheels: Int = 5
    override val wheelSize: Double = 5.0
    override fun accelerate() {
        moveForward = true
        stop = false
    }

    override fun stop() {
        moveForward = false
        stop = true
    }
}

In this example, we have defined a class Bike that implements interface Vehicle and WheelerType. By implementing these interface, Bike got features such as accelerate, stop, number of wheels, wheel size etc.

The class Bike implements all the methods and properties defined in both Vehicle and WheelerType. If any of them weren’t defined, you’d receive a build error.

Can you notice Multiple Interface in a class here ?

Let me know in the comment section below

Let’s look at a complete example now.

interface Vehicle
{
  fun accelerate()
  fun stop()
}

enum class Direction {
   Left, Right
}
interface VehicleWithDirection: Vehicle
{
  fun turn(direction: Direction = Direction.Left)
}

interface WheelerType
{
  val numOfWheels: Int
  val wheelSize: Double
}

class Bike: VehicleWithDirection, WheelerType {
    var moveForward = false
    var stop = false

    override val numOfWheels: Int = 5
    override val wheelSize: Double = 5.0

    override fun accelerate() {
        moveForward = true
        stop = false
        println("Bike accelerated")
    }

    override fun stop() {
        moveForward = false
        stop = true
        println("Bike Stopped")
    }
    override fun turn(direction: Direction) {
       println("Current turn: ${direction}")
    }
}

fun main(Args:Array<String>)
{
  val bike = Bike()
  bike.accelerate()
  bike.turn()  // Default turn Left
  bike.turn(Direction.Right)  // Now, bike turns Right.
  bike.stop()
}

This is complete example to show how to use inheritance in interface in kotlin, how to use multiple interface in kotlin etc.

Let me know in comment section below if you have any confusion –

Summary

  • You can define interface in kotlin as below –

    interface MyInterface {
        val name: String
    }
    
  • You can implement interface as –

    interface MyInterface {
       val name: String  //abstract variable
    }
     
    class MyClass: MyInterface {
       override val name: String
    }
    
  • Multiple interface can be implemented as –

    class ClassName: InterfaceNameA, InterfaceNameB {
     
    // Overrides Methods present in different interfaces...
     
    }
    

    If there are more than one methods with same name in interfaces, then, you can resolve conflicts by providing own implementation of method in class that implements class.

  • We can inherit interface A from other interface B. Example to apply interface inheritance in kotlin is –

    interface Named {
        val name: String
    }
     
    interface Person : Named {
        val firstName: String
        val lastName: String
         
        override val name: String get() = "Your name is $firstName $lastName"
    }
    

Exercises

  1. Create an interface Area that have a read-only property area of type Double.
  2. Implement Area with classes representing Square, Triangle, and Circle

Support Us

If you like Tutorialwing and would like to contribute, you can email an article on any educational topic at tutorialwing@gmail.com. We would love to publish your article. See your article on Tutorialwing and help others with your knowledge. Follow Facebook, LinkedIn, Google+, Twitter, Youtube for latest updates.
Greetings!
We have recently published 100+ articles on android tutorials with kotlin and java. If you need, you may visit Android Tutorial for beginners page. You can also check Kotlin Tutorial for beginners