Sobes.tech
Junior — Middle

Milliseid meetodeid saab kasutada juba rakendatud klassi funktsionaalsuse laiendamiseks?

sobes.tech AI

Vastus AI-lt

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.

Java example of inheritance:

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");
    }
}

Kotlin extension function example:

fun String.addExclamation(): String {
    return this + "!"
}

val greeting = "Hello".addExclamation() // "Hello!"

The method choice depends on the specific task and project constraints.