Bird
Raised Fist0
Kotlinprogramming~10 mins

Interface with default implementations in Kotlin - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Interface with default implementations
Define Interface
↓
Add Default Method
↓
Implement Interface in Class
↓
Use Class Instance
↓
Call Method
↓
Class Override?
Yes→Use Override
No↓
Use Default Implementation
This flow shows how an interface with a default method is defined, implemented by a class, and how method calls use either the class override or the default implementation.
Execution Sample
Kotlin
interface Greeter {
    fun greet() {
        println("Hello from default!")
    }
}

class Friendly : Greeter {
    override fun greet() {
        println("Hi there!")
    }
}

fun main() {
    val f = Friendly()
    f.greet()
}
This code defines an interface with a default greet method, a class that overrides it, and calls greet on the class instance.
Execution Table
StepActionEvaluationOutput
1Define interface Greeter with default greet()Interface created with default greet()
2Define class Friendly implementing GreeterClass Friendly ready, overrides greet()
3Create instance f of Friendlyf is Friendly instance
4Call f.greet()Check if Friendly overrides greet() -> YesHi there!
5End of main()Program ends
💡 Program ends after calling overridden greet() method on Friendly instance
Variable Tracker
VariableStartAfter Step 3Final
fundefinedFriendly instance createdFriendly instance
Key Moments - 2 Insights
Why does calling greet() on Friendly print "Hi there!" instead of the default message?
Because Friendly overrides the greet() method, so the call uses the class's version, as shown in execution_table step 4.
What happens if Friendly does not override greet()?
The default greet() from the interface is used, printing "Hello from default!". This is the fallback behavior if no override exists.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table at step 4, what output is produced when f.greet() is called?
A"Hello from default!"
BNo output
C"Hi there!"
DCompilation error
💡 Hint
Check the Output column at step 4 in the execution_table.
If the class Friendly did not override greet(), what would be the output at step 4?
A"Hi there!"
B"Hello from default!"
CNo output
DRuntime error
💡 Hint
Refer to key_moments answer 2 about default method usage.
In variable_tracker, what is the value of variable 'f' after step 3?
AFriendly instance
Bnull
Cundefined
DGreeter instance
💡 Hint
Look at variable_tracker row for 'f' after step 3.
Concept Snapshot
interface InterfaceName {
    fun method() { // default implementation
        // code
    }
}

class MyClass : InterfaceName {
    override fun method() { // optional override
        // code
    }
}

- Interfaces can have methods with default code.
- Classes can override these methods or use defaults.
- Calling the method uses override if present, else default.
Full Transcript
This example shows how Kotlin interfaces can have default method implementations. The interface Greeter defines greet() with a default print statement. The class Friendly implements Greeter and overrides greet() with its own print statement. When we create an instance of Friendly and call greet(), the overridden method runs, printing "Hi there!". If Friendly did not override greet(), the default method from the interface would run instead. This allows interfaces to provide common behavior while letting classes customize it. The execution table traces each step: defining interface and class, creating instance, calling method, and output. The variable tracker shows the instance creation. Key moments clarify why the overridden method runs and what happens without override. The quiz tests understanding of output and variable states. The snapshot summarizes syntax and behavior for quick reference.

Practice

(1/5)
1.

What is the main purpose of providing a default implementation in a Kotlin interface?

interface Example { fun greet() { println("Hello") } }

easy
A. To allow classes to use the function without implementing it themselves
B. To prevent classes from overriding the function
C. To make the interface abstract and unusable
D. To force all classes to implement the function

Solution

  1. Step 1: Understand default implementations in interfaces

    Default implementations provide a function body inside the interface itself.
  2. Step 2: Effect on implementing classes

    Classes can use this default function without writing their own version.
  3. Final Answer:

    To allow classes to use the function without implementing it themselves -> Option A
  4. Quick Check:

    Default implementation means no need to override [OK]
Hint: Default means usable without override [OK]
Common Mistakes:
  • Thinking default means function cannot be overridden
  • Confusing default implementation with abstract function
  • Believing interface becomes unusable with default methods
2.

Which of the following is the correct syntax for a Kotlin interface with a default implementation of a function fun info()?

easy
A. interface Info { fun info() = println("Info") }
B. interface Info { fun info() println("Info") }
C. interface Info { fun info() -> println("Info") }
D. interface Info { fun info; println("Info") }

Solution

  1. Step 1: Recall Kotlin interface function syntax

    Default implementations use = followed by expression or block with braces.
  2. Step 2: Check each option

    interface Info { fun info() = println("Info") } uses = with println(), which is correct syntax for default implementation.
  3. Final Answer:

    interface Info { fun info() = println("Info") } -> Option A
  4. Quick Check:

    Default function uses = expression [OK]
Hint: Default functions use = for single expression [OK]
Common Mistakes:
  • Using braces without = in interface default functions
  • Using arrow -> instead of =
  • Writing function body outside interface
3.

What will be the output of the following Kotlin code?

interface Printer {
    fun print() { println("Printing from interface") }
}

class Document : Printer {
    override fun print() { println("Printing from Document") }
}

fun main() {
    val doc: Printer = Document()
    doc.print()
}
medium
A. Printing from interface
B. Compilation error due to override
C. Printing from Document
D. Runtime error

Solution

  1. Step 1: Understand override behavior

    The class Document overrides the print() function from Printer interface.
  2. Step 2: Check which print() is called

    Even though the variable type is Printer, the actual object is Document, so overridden print() runs.
  3. Final Answer:

    Printing from Document -> Option C
  4. Quick Check:

    Overridden method runs on object type [OK]
Hint: Overridden methods run from actual object type [OK]
Common Mistakes:
  • Thinking interface default method runs instead of override
  • Confusing variable type with object type
  • Expecting compilation error for override
4.

Identify the error in this Kotlin code snippet:

interface Logger {
    fun log() { println("Logging") }
}

class FileLogger : Logger {
    fun log() { println("File logging") }
}
medium
A. FileLogger cannot implement Logger without constructor
B. Missing override keyword in FileLogger's log() function
C. Interface functions cannot have bodies
D. log() function must be abstract in interface

Solution

  1. Step 1: Check interface function declaration

    Logger interface has a default implementation of log().
  2. Step 2: Check FileLogger's log() function

    It defines log() but misses the override keyword, which is required.
  3. Final Answer:

    Missing override keyword in FileLogger's log() function -> Option B
  4. Quick Check:

    Override keyword required when overriding [OK]
Hint: Override keyword is mandatory for overrides [OK]
Common Mistakes:
  • Forgetting override keyword
  • Thinking interface functions cannot have bodies
  • Assuming abstract keyword needed in interface
5.

Given this Kotlin interface and classes, what will be the output when main() runs?

interface Speaker {
    fun speak() { println("Speaking from Speaker") }
}

class Person : Speaker

class Robot : Speaker {
    override fun speak() { println("Speaking from Robot") }
}

fun main() {
    val list: List<Speaker> = listOf(Person(), Robot())
    for (item in list) {
        item.speak()
    }
}
hard
A. Compilation error due to missing override in Person
B. Speaking from Person Speaking from Robot
C. Speaking from Speaker Speaking from Speaker
D. Speaking from Speaker Speaking from Robot

Solution

  1. Step 1: Analyze Person class

    Person does not override speak(), so it uses Speaker's default implementation.
  2. Step 2: Analyze Robot class

    Robot overrides speak(), so its own version runs.
  3. Step 3: Loop output

    First item (Person) prints "Speaking from Speaker", second (Robot) prints "Speaking from Robot".
  4. Final Answer:

    Speaking from Speaker Speaking from Robot -> Option D
  5. Quick Check:

    Default + override methods run accordingly [OK]
Hint: Classes use default unless overridden [OK]
Common Mistakes:
  • Expecting Person to print "Speaking from Person"
  • Thinking missing override causes error
  • Assuming both print Robot's message
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard