Junior — Middle
What methods can be used to extend the functionality of an already implemented class?
sobes.tech AI
Answer from AI
To extend the functionality of an already implemented class in Android (Java/Kotlin), several methods can be used:
-
Inheritance — create a subclass that extends the base class and adds or overrides methods.
-
Composition — include an instance of an existing class in a new class and delegate calls, adding new logic.
-
Decorator — wrap an object in another object that adds functionality while preserving the interface.
-
Extension Functions (in Kotlin) — add new functions to existing classes without inheritance.
Example of inheritance in Java:
public class BaseClass {
public void doSomething() {
System.out.println("Base implementation");
}
}
public class ExtendedClass extends BaseClass {
@Override
public void doSomething() {
super.doSomething();
System.out.println("Extended functionality");
}
}
Example of extension function in Kotlin:
fun String.addExclamation(): String {
return this + "!"
}
val greeting = "Hello".addExclamation() // "Hello!"
The choice of method depends on the specific task and project constraints.