Junior — Middle
What methods can be used to add functionality to an existing class?
sobes.tech AI
Answer from AI
In Android (and in Java/Kotlin in general), functionality can be added to an existing class in the following ways:
-
Inheritance — create a subclass that extends or overrides the behavior of the base class.
-
Composition — include an instance of an existing class in a new class and use its methods, adding new logic.
-
Extension functions — in Kotlin, you can add new functions to existing classes without inheritance or modifying the source code:
fun String.addExclamation() = this + "!"
val greeting = "Hello".addExclamation() // Hello!
-
Delegation — use the delegation pattern to pass method calls to another object.
-
Decorator — wrap an object in another object that adds new functionality.
Each method has its advantages and is used depending on the task and project constraints.