Multiple Interfaces
Part of the Object Oriented Programming section of Coddy's Kotlin journey. Lesson 24 of 57.
A class can implement several interfaces, separated by commas. It has to implement the members of all of them:
interface Switchable {
var isOn: Boolean
fun toggle() { isOn = !isOn }
}
interface Dimmable {
var level: Int
}
class Lamp : Switchable, Dimmable {
override var isOn = false
override var level = 100
}Inside main:
val lamp = Lamp()
lamp.toggle()
lamp.level = 40
println("${lamp.isOn} ${lamp.level}")Output:
true 40A class can extend one class and implement interfaces in the same header. Only the superclass has a constructor call:
open class Device(val name: String)
interface Rechargeable {
fun charge(): String
}
class Phone(name: String) : Device(name), Rechargeable {
override fun charge() = "$name is charging"
}Inside main:
println(Phone("Pixel").charge())Output:
Pixel is chargingWhen two interfaces both give the same method a default body, the class must override it and decide what to do. super<Name>.method() calls the version of one particular interface:
interface Camera {
fun describe() = "takes photos"
}
interface Telephone {
fun describe() = "makes calls"
}
class SmartPhone : Camera, Telephone {
override fun describe() = super<Telephone>.describe() + " and " + super<Camera>.describe()
}Inside main:
println(SmartPhone().describe())Output:
makes calls and takes photosAn interface can extend other interfaces. A class that implements the combined interface must provide the members of all of them, and it counts as each of them:
interface Named {
val name: String
}
interface Contact : Named {
val email: String
fun card() = "$name <$email>"
}
class Person(override val name: String, override val email: String) : ContactInside main:
val ada = Person("Ada", "ada@example.com")
val named: Named = ada
println(ada.card())
println(named.name)Output:
Ada <ada@example.com>
AdaChallenge
EasyTwo interfaces describe a smart device: Switchable requires isOn (a read-only Boolean for callers) and toggle(), and Dimmable requires a writable brightness. Make SmartLamp implement both: it starts off at brightness 100, toggle() flips it on and off, a brightness outside 0 to 100 is clamped by the setter, and status() returns on 70% or off.
The supplied code reads commands toggle or a brightness number, applies them to one lamp and prints status() after each, then checks that the lamp is Switchable and Dimmable.
Your code goes in Switchable.kt, Dimmable.kt and SmartLamp.kt. Main.kt holds the supplied input/output code and cannot be edited.
Try it yourself
fun main() {
// Supplied input/output code: keep it as it is
val input = generateSequence(::readLine).toList()
val lamp = SmartLamp()
for (cmd in input) {
if (cmd == "toggle") lamp.toggle() else lamp.brightness = cmd.toInt()
println(lamp.status())
}
println("switchable: ${(lamp as Any) is Switchable}, dimmable: ${(lamp as Any) is Dimmable}")
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Object Oriented Programming
1Classes and Objects
Working With FilesDefining ClassesPrimary Constructorsinit Blocks and ValidationSecondary ConstructorsRecap - Library Card4Inheritance
Open Classes and SubclassesOverriding Memberssuper and ConstructorsAbstract ClassesRecap - Staff Directory2Properties and Encapsulation
Custom AccessorsVisibility ModifiersPrivate Setterslazy and lateinitRecap - Bank Account5Interfaces
Declaring InterfacesDefault MethodsMultiple InterfacesInterfaces as TypesRecap - Payment Methods8Generics
Generic FunctionsGeneric ClassesType ConstraintsVariance With in and outRecap - Priority Queue11Project: Library Management
Books and MembersBorrowing BooksPractice on your own: Kotlin playground