Kotlin Interfaces
In Kotlin, an interface is a blueprint of a class that defines a set of methods and properties, but does not provide an implementation. An interface can be implemented by one or more classes, and a class can implement one or more interfaces.
To define an interface in Kotlin, you use the interface
keyword, followed by the name of the interface, and then the list of method signatures and property declarations. Here's an example of an interface:
interface Shape { fun area(): Double }Sww:ecruow.theitroad.com
In this example, we define an interface called Shape
. The Shape
interface has one method called area()
. Since area()
has no implementation, we do not provide a body for it.
Here's an example of a class that implements the Shape
interface and provides an implementation for area()
:
class Rectangle(val width: Double, val height: Double) : Shape { override fun area(): Double { return width * height } }
In this example, we define a class called Rectangle
that implements the Shape
interface. We provide the implementation of area()
by multiplying the width
and height
properties of the rectangle.
Note that since Shape
is an interface, we cannot create an instance of it directly. However, we can create an instance of Rectangle
, which implements the Shape
interface.
Kotlin interfaces can also include property declarations, which are abstract by default. Here's an example of an interface that includes a property declaration:
interface Person { val name: String fun sayHello() }
In this example, we define an interface called Person
. The Person
interface has one property called name
, which is abstract by default, and one method called sayHello()
, which has no implementation. Any class that implements the Person
interface must provide an implementation for both name
and sayHello()
.