Interface Basics
In this page:
Declaring an Interface
An interface defines a set of functions and properties that any implementing class agrees to provide, without specifying how they must be implemented.
Example: Declaring an Interface
interface Greetable {
fun greet(): String
}
class Person(val name: String) : Greetable {
override fun greet(): String = "Hello, I am $name"
}
fun main() {
val person = Person("Ana")
println(person.greet())
}
Login to try C/C++/Java/PHP code in the editor
Default Implementations in Interfaces
An interface function can include a body directly, providing a default implementation that classes may use as-is or override with their own version.
Example: Default Implementations in Interfaces
interface Greetable {
fun greet(): String = "Hello there!"
}
class Robot : Greetable
fun main() {
val robot = Robot()
println(robot.greet())
}
Login to try C/C++/Java/PHP code in the editor
Implementing an Interface
A class implements an interface by listing it after a colon, then providing override for any of its abstract members that have no default implementation.
Example: Implementing an Interface
interface Playable {
fun play(): String
}
class Song(val title: String) : Playable {
override fun play(): String = "Playing $title"
}
fun main() {
val song = Song("Kotlin Beats")
println(song.play())
}
Login to try C/C++/Java/PHP code in the editor
Properties in Interfaces
Interfaces can declare abstract properties too, which implementing classes must provide a value or backing implementation for.
Example: Properties in Interfaces
interface HasArea {
val area: Double
}
class Square(val side: Double) : HasArea {
override val area: Double
get() = side * side
}
fun main() {
val square = Square(4.0)
println("Area: ${square.area}")
}
Login to try C/C++/Java/PHP code in the editor
- Trying to store constructor-style state in an interface; interfaces cannot have constructors or backing-field state, only abstract or default-implemented members.
- Forgetting to implement a required interface method, which the compiler flags as a missing override in the implementing class.
- Assuming an interface method without a body is automatically abstract-only; interfaces can also provide default implementations directly.
interfacedeclares a contract of functions and properties that implementing classes must fulfill.- Interface members are abstract by default but can also provide a default implementation directly in the interface.
- A class implements an interface with
class MyClass : MyInterface { ... }, providingoverridefor any required members. - A class can implement multiple interfaces, unlike single-inheritance from classes.
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: