Junior — Middle
Explain the differences between inheritance and composition in object-oriented programming.
sobes.tech AI
Answer from AI
Inheritance and composition are two main ways of reusing code in object-oriented programming, but they have different approaches and goals.
Inheritance is a mechanism where one class (subclass) inherits properties and methods from another class (superclass). This creates an "is-a" hierarchy. For example, a Cat class inherits from an Animal class, meaning a cat is an animal.
Composition is when one object contains another object and uses its functionality, meaning a "has-a" relationship. For example, a Car class may contain an Engine object.
Main differences:
- Inheritance creates a tight coupling between classes, while composition is more flexible and allows changing components at runtime.
- Inheritance is better suited for extending behavior, while composition is for combining functionalities.
- Composition promotes loose coupling and better modularity.
Example in Kotlin:
// Inheritance
open class Animal {
open fun sound() = "Some sound"
}
class Cat : Animal() {
override fun sound() = "Meow"
}
// Composition
class Engine {
fun start() = "Engine started"
}
class Car(private val engine: Engine) {
fun startCar() = engine.start()
}
In Android development, it is preferable to use composition to avoid tight coupling and improve testability of the code.