Open In App

Kotlin Interfaces

Last Updated : 09 Feb, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In Kotlin, an interface is a collection of abstract methods and properties that define a common contract for classes that implement the interface. An interface is similar to an abstract class, but it can be implemented by multiple classes, and it cannot have state.

Interfaces are custom types provided by Kotlin that cannot be instantiated directly. Instead, these define a form of behavior that the implementing types have to follow. With the interface, you can define a set of properties and methods, that the concrete types must follow and implement.

Creating Interfaces –

The interface definition in Kotlin begins with the interface keyword followed by the name of the interface, followed by the curly braces within which the members of the interface reside. The difference is that the members will have no definition of their own. These definitions will be provided by the conforming types. 

Example:

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

Implementing Interfaces –

An interface can be implemented by a class or an object. When implementing an interface, the conforming type must provide the definition for all of its members. To implement an interface, the name of the custom type is followed by a colon and the name of the interface which is to be implemented.

class Car: Vehicle

Example to demonstrate an interface in Kotlin – 

Java




interface Vehicle {
    fun start()
    fun stop()
}
 
class Car : Vehicle {
    override fun start()
    {
        println("Car started")
    }
 
    override fun stop()
    {
        println("Car stopped")
    }
}
 
fun main()
{
    val obj = Car()
    obj.start()
    obj.stop()
}


Output:

Car started
Car stopped

Explanation: In this program, the interface Vehicle declares two methods start() and stop(), which need to be overridden. The class Car implements the interface using the class-literal syntax and overrides the two methods using the override keyword. Finally, the main function creates an object of class Car and calls the two methods.

Default values and Default Methods –

Methods in an interface can have default values for its parameters. If the value for a parameter is not provided at the time of function call, then the default value is used. Also, the methods can have default implementations. These are used in the case where the method is not overridden. Example to demonstrate default value and default methods – 

Java




interface FirstInterface {
    fun add(a: Int, b: Int = 5)
    fun print()
    {
        println("This is a default method defined in the interface")
    }
}
class InterfaceDemo : FirstInterface {
    override fun add(a: Int, b: Int)
    {
        val x = a + b
        println("Sum is $x")
    }
 
    override fun print()
    {
        super.print()
        println("It has been overridden")
    }
}
 
fun main()
{
    val obj = InterfaceDemo()
    println(obj.add(5))
    obj.print()
}


Output:

Sum is 10
This is a default method defined in the interface
It has been overridden

Explanation: In the above program, the FirstInterface defines two methods add() and print(). The add() method has two parameters, one of which is provided a default value of 5. Also, the print() method is provided a default implementation. So, when class InterfaceDemo implements the interface, it overrides both the methods and calls the default implementation of print() using the super keyword. Also, in main function only one argument is specified when calling add method, since the second one is given a default value.

Properties in interface –

Just like methods, interfaces can also contain properties. However, since the interface doesn’t have a state that is, they can’t be instantiated, so there are no backing fields to hold their values. Hence, the fields in the interface are either left abstract or are provided an implementation. Example to demonstrate interface properties – 

Java




interface InterfaceProperties {
    val a : Int
    val b : String
        get() = "Hello"
}
 
class PropertiesDemo : InterfaceProperties {
    override val a : Int = 5000
    override val b : String = "Property Overridden"
}
 
fun main()
{
    val x = PropertiesDemo()
    println(x.a)
    println(x.b)
}


Output:

5000
Property Overridden

Explanation: In the above program, InterfaceProperties defines two properties a which is an integer, and b of type String which is provided a getter. The class PropertiesDemo implements InterfaceProperties and overrides the two properties, providing them value. The function main creates an object of the class and accesses the properties using dot-syntax.

Inheritance in Interfaces –

Interfaces in Kotlin can also inherit other interfaces. When an interface extends another interface, it can add its own properties and methods, and the implementing type has to provide a definition for all the properties and methods in both the interfaces. An interface can inherit more than one interface. Example to demonstrate interface inheritance – 

Java




interface Dimensions {
    val length : Double
    val breadth : Double
}
 
interface CalculateParameters : Dimensions {
    fun area()
    fun perimeter()
}
 
class XYZ : CalculateParameters {
    override val length : Double
        get() = 10.0
    override val breadth : Double
        get()= 15.0
 
    override fun area()
    {
        println("Area is ${length * breadth}")
    }
 
    override fun perimeter()
    {
        println("Perimeter is ${2*(length+breadth)}")
    }
}
 
fun main()
{
    val obj = XYZ()
    obj.area()
    obj.perimeter()
}


Output:

Area is 150.0
Perimeter is 50.0

Explanation: In the program, the interface Dimensions define two properties length and breadth. The interface CalculatedParameters inherits Dimensions and adds two methods area() and perimeter(). The class XYZ implements CalculatedParameters and overrides both the properties and methods, which then invoked in main function.

Multiple Interface Implementation –

Since classes in Kotlin follow the concept of single inheritance, that is, each class can inherit only class, however, in case of interfaces a class supports multiple inheritance, also known as multiple conformance in Kotlin. A class can implement more than one interface, provided that it provides a definition for all the members of the interface. Example to demonstrate multiple interface implementation – 

Java




interface InterfaceProperties {
    val a : Int
    val b : String
        get() = "Hello"
}
 
interface InterfaceMethods {
    fun description()
}
 
class MultipleInterface : InterfaceProperties, InterfaceMethods {
    override val a : Int
        get() = 50
 
    override fun description()
    {
        println("Multiple Interfaces implemented")
    }
}
fun main()
{
    val obj = MultipleInterface()
    obj.description()
}


Output:

Multiple Interfaces implemented

Explanation: In the program, two interfaces InterfaceProperties and InterfaceMethods are defined. These interfaces are implemented by the class MultipleInterface and then the methods are invoked in main function.

Advantages of using interfaces in Kotlin:

  1. Abstraction: Interfaces provide a way to define a common contract between different classes without specifying the implementation details. This enables you to create abstractions that improve the modularity and maintainability of your code.
  2. Polymorphism: Interfaces allow you to create objects of different types that have the same interface, which enables polymorphic behavior.
  3. Code Reusability: Interfaces provide a way to reuse code by allowing multiple classes to implement the same interface and share the same abstract methods and properties.

Disadvantages of using interfaces in Kotlin:

  1. Limited Implementation: Interfaces can only contain abstract methods and properties, so they provide limited implementation details.
  2. Complexity: Interfaces can make your code more complex, especially if you have many classes that implement multiple interfaces.

Reference:

A popular book for learning Kotlin is “Kotlin in Action” by Dmitry Jemerov and Svetlana Isakova. This book provides a comprehensive introduction to the Kotlin programming language, including its syntax, libraries, and best practices, with many hands-on examples and exercises.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads