Kotlin Kotlin Classes and Object-Oriented Programming 2 — Questions and Answers
Question 1: How do you implement an interface in Kotlin?
- Using the `implements` keyword
- Using `:` after the class name followed by the interface name (Correct answer)
- Using the `with` keyword
- Using `@Interface` annotation
Correct answer: Using `:` after the class name followed by the interface name
In Kotlin, both inheritance and interface implementation use the `:` syntax after the class name.
Question 2: What is the purpose of the `init` block in a Kotlin class?
- To declare class fields
- To execute initialization code as part of the primary constructor (Correct answer)
- To define static methods
- To mark the class as immutable
Correct answer: To execute initialization code as part of the primary constructor
The `init` block runs initialization logic immediately after the primary constructor, in the order it appears in the class body.
Question 3: Which Kotlin feature allows a class to delegate interface implementation to another object?
- Extension functions
- Class delegation using `by` (Correct answer)
- Companion objects
- Abstract members
Correct answer: Class delegation using `by`
Kotlin supports class delegation with the `by` keyword, allowing interface implementations to be forwarded to a wrapped object automatically.
Question 4: What is an object declaration in Kotlin?
- An instance of an anonymous class
- A singleton object defined with the `object` keyword (Correct answer)
- A class with all-static members
- A companion to a class
Correct answer: A singleton object defined with the `object` keyword
An `object` declaration in Kotlin creates a singleton — a class with exactly one instance created lazily on first access.
Question 5: What does the `override` keyword do in Kotlin?
- Marks a function as final
- Explicitly overrides a member from a superclass or interface (Correct answer)
- Creates a new version of a private method
- Allows calling the parent's constructor
Correct answer: Explicitly overrides a member from a superclass or interface
`override` is required in Kotlin to explicitly mark that a member is intentionally overriding a superclass or interface member.
Question 6: What does `object : Interface` syntax create in Kotlin?
- A named object implementing an interface
- An anonymous object implementing the interface inline (Correct answer)
- A companion object
- A sealed subclass
Correct answer: An anonymous object implementing the interface inline
This syntax creates an anonymous object (similar to Java's anonymous class) that implements the specified interface.
How do you implement an interface in Kotlin?