An interface lets you define a set of actions that different classes can share. It helps organize code by saying what actions are possible, without saying how they work.
Interface declaration and implementation in Kotlin
interface InterfaceName { fun action1() fun action2(): ReturnType // properties can also be declared val propertyName: Type } class ClassName : InterfaceName { override fun action1() { // implementation } override fun action2(): ReturnType { // implementation } override val propertyName: Type = value }
Use interface keyword to declare an interface.
Classes use : to say they implement an interface and must provide all its functions and properties.
Drivable with one function. Car class implements it by providing the drive function.interface Drivable { fun drive() } class Car : Drivable { override fun drive() { println("Car is driving") } }
Person class implements it by overriding the property in the constructor.interface Named { val name: String } class Person(override val name: String) : Named
ConsoleLogger class uses the default log method without extra code.interface Logger { fun log(message: String) { println("Log: $message") } } class ConsoleLogger : Logger
This program defines an Animal interface with a sound function. Dog and Cat classes implement it with their own sounds. The main function creates objects and calls their sounds.
interface Animal { fun sound() } class Dog : Animal { override fun sound() { println("Woof!") } } class Cat : Animal { override fun sound() { println("Meow!") } } fun main() { val dog: Animal = Dog() val cat: Animal = Cat() dog.sound() cat.sound() }
Interfaces cannot hold state (no backing fields), only abstract properties or methods with default implementations.
Classes must use override keyword to implement interface members.
Interfaces help write flexible and reusable code by focusing on what actions are possible.
Interfaces define a contract of functions and properties without implementation details.
Classes implement interfaces by providing the actual code for the functions and properties.
This helps organize code and allows different classes to be used interchangeably.
Practice
interface in Kotlin?Solution
Step 1: Understand what an interface is
An interface in Kotlin declares functions and properties but does not provide their implementation.Step 2: Compare options with interface purpose
To define a contract with functions and properties without implementation correctly states that interfaces define a contract without implementation. Other options describe features unrelated to interfaces.Final Answer:
To define a contract with functions and properties without implementation -> Option DQuick Check:
Interface = Contract without code [OK]
- Thinking interfaces can create objects directly
- Confusing interfaces with classes that store data
- Believing interfaces inherit from classes
Solution
Step 1: Recall Kotlin interface syntax
Interfaces are declared with the keywordinterfacefollowed by the name and curly braces containing function declarations without parentheses after the name.Step 2: Check each option
interface MyInterface { fun doWork() } matches the correct syntax. class MyInterface { fun doWork() } usesclassinstead ofinterface. fun interface MyInterface { fun doWork() } usesfun interfacewhich is for functional interfaces but requires a single abstract method and different usage. interface MyInterface() { fun doWork() } incorrectly adds parentheses after the interface name.Final Answer:
interface MyInterface { fun doWork() } -> Option AQuick Check:
Interface syntax = interface Name { ... } [OK]
- Using class keyword instead of interface
- Adding parentheses after interface name
- Confusing fun interface with regular interface
interface Greeter {
fun greet(): String
}
class FriendlyGreeter : Greeter {
override fun greet() = "Hello!"
}
fun main() {
val greeter: Greeter = FriendlyGreeter()
println(greeter.greet())
}Solution
Step 1: Understand interface implementation
The interfaceGreeterdeclares a functiongreet(). The classFriendlyGreeterimplements this interface and overridesgreet()to return "Hello!".Step 2: Trace the main function output
Inmain(), an instance ofFriendlyGreeteris assigned to a variable of typeGreeter. Callinggreet()on this instance returns "Hello!" which is printed.Final Answer:
Hello! -> Option CQuick Check:
Interface method call returns overridden string [OK]
- Expecting interface name printed instead of method result
- Thinking it causes compilation error without implementation
- Confusing class name with output
interface Animal {
fun sound(): String
}
class Dog : Animal {
fun sound() = "Bark"
}Solution
Step 1: Check interface function implementation rules
When a class implements an interface function, it must use theoverridekeyword to provide the implementation.Step 2: Analyze the Dog class
TheDogclass definessound()withoutoverride. This causes a compilation error because it does not properly override the interface method.Final Answer:
Dog class must override sound() with 'override' keyword -> Option AQuick Check:
Override keyword required for interface methods [OK]
- Omitting the override keyword
- Thinking interface methods can't have return types
- Making interface implementation optional
main() is run?interface Calculator {
fun calculate(x: Int, y: Int): Int
}
class Adder : Calculator {
override fun calculate(x: Int, y: Int) = x + y
}
class Multiplier : Calculator {
override fun calculate(x: Int, y: Int) = x * y
}
fun main() {
val calculators: List<Calculator> = listOf(Adder(), Multiplier())
for (calc in calculators) {
println(calc.calculate(3, 4))
}
}Solution
Step 1: Understand interface implementations
Two classes implementCalculator:Adderadds two numbers,Multipliermultiplies them.Step 2: Trace the loop output
The list contains anAdderand aMultiplier. Callingcalculate(3,4)onAdderreturns 7, onMultiplierreturns 12. These are printed in order.Final Answer:
7 12 -> Option BQuick Check:
Adder + Multiplier outputs 7 and 12 [OK]
- Mixing order of outputs
- Expecting string concatenation instead of arithmetic
- Thinking interface list causes error
Ready to prove it?
Pass the test and this pattern moves unknown
