What can replace inheritance and what are the alternative methods?
sobes.tech AI
Answer from AI
-
Object Composition: Instead of inheritance, where one class inherits properties and behavior from another, an object can contain an instance of another object and use its functionality (Delegation pattern).
-
Interfaces: A class can implement one or more interfaces, thereby committing to provide certain behavior. This allows achieving polymorphism without a strict inheritance hierarchy.
-
Extension Functions in Kotlin: Allow adding new functions to existing classes without modifying their source code, simulating the addition of behavior.
-
Traits (a concept from other languages, in Kotlin can be implemented via interfaces with default methods): A set of methods that can be used by classes through "mixing". Interfaces with default method implementations in Kotlin partially realize this concept.
Example of composition:
class Engine {
fun start() {
// Engine start logic
}
}
class Car {
private val engine = Engine() // Composition
fun drive() {
engine.start()
// Car driving logic
}
}
Example of an interface:
interface Drawable {
fun draw()
}
class Circle : Drawable {
override fun draw() {
// Circle drawing logic
}
}
class Square : Drawable {
override fun draw() {
// Square drawing logic
}
}
Example of an extension function:
fun String.removeVowels(): String {
return this.replace("[aeiouAEIOU]".toRegex(), "")
}
fun main() {
val text = "Hello World"
println(text.removeVowels()) // Output: Hll Wrld
}