Classes

Kotlin Interfaces

Defining Interfaces

Kotlin interfaces define contracts with default implementations.

What is a Kotlin Interface?

In Kotlin, an interface is a contract that a class can implement. Unlike classes, interfaces can contain abstract methods as well as method implementations, known as default implementations. This allows for greater flexibility and reusability in code design.

Defining an Interface

A Kotlin interface is declared using the interface keyword. Within an interface, you can define abstract properties and functions. Here's a simple example:

Implementing an Interface

Classes that implement an interface must provide concrete implementations of the abstract members of the interface. Here's how a class implements the Drivable interface:

Default Implementations in Interfaces

Let's enhance our Drivable interface with a default implementation:

Using Interfaces with Default Methods

Here's how a class can use the default method:

Multiple Interface Inheritance

Kotlin allows a class to implement multiple interfaces. When a class implements multiple interfaces that contain methods with the same signature, the class must override those methods to resolve any conflicts. Here's an example:

In this example, the FlyingCar class successfully implements both the Drivable and Flyable interfaces, providing specific implementations for each interface's methods.

Previous
Inheritance