interface
- Kotlin course
- Intermediate
- Lesson 11/116
- 5 min
Learn to implement interfaces.
interface
An interface defines a contract that implementing classes fill in. In Kotlin an interface can hold both bodyless methods and bodied default methods; however it cannot hold state.
Example: interface Drawable { fun draw(): String }. Classes implementing this interface must override fun draw(): String. A class can implement multiple interfaces: class Foo : A, B. Interfaces take no constructor parameters; this distinguishes them from abstract classes.
Implementing an interface
A class implements an interface with :. It must override the bodyless methods of the interface. Multiple interfaces are listed with commas.
Example: class Circle(val radius: Double) : Drawable { override fun draw() = "circle" }. Here Circle implements Drawable and also carries its own radius property. When implementing an interface, no constructor call is made (no parentheses); only the interface name is written. This is a different rule from class inheritance.
Practice The Drawable interface and the Circle class
Define an interface named Drawable with a method fun draw(): String. Define a class named Circle with a primary constructor taking val radius: Double that implements the Drawable interface. Its override fun draw(): String returns "Circle drawn: radius $radius". In main create a Circle(3.0) instance and print the result of draw().
Starter code
// Drawable interface
// draw method signature
// Circle class, implements Drawable
// override to return radius text
// instantiate Circle in main, print drawSample solution
interface Drawable {
fun draw(): String
}
class Circle(val radius: Double) : Drawable {
override fun draw(): String {
return "Circle drawn: radius $radius"
}
}
fun main() {
val c = Circle(3.0)
println(c.draw())
}Expected output
Circle drawn: radius 3.0
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which of the following can a Kotlin interface not contain?
- A bodyless method
- A bodied default method
- An abstract method signature
- An instance field (state) Correct answer
Explanation: Interfaces cannot hold state; they only define behavior.
2 Match the interface concepts
| Term | Meaning |
|---|---|
interface Drawable |
Contract definition |
fun draw(): String |
Bodyless method |
: Drawable |
Implementation clause |
override fun draw() |
Filling in the class |
3 Complete the interface implementation
class Circle(val radius: Double) : ____ {
override fun draw() = "circle"
}
class Circle(val radius: Double) : Drawable {
override fun draw() = "circle"
}
Explanation: The interface name is written after :, without a constructor call.