Sobes.tech
Junior — Middle

How can you add extended functionality to existing classes in Java without modifying their source code?

sobes.tech AI

Answer from AI

In Java, to add extended functionality to existing classes without modifying their source code, the "Decorator" pattern or composition is often used.

Additionally, starting from Java 8, default methods in interfaces can be used, which allow adding methods with implementations without changing the classes that implement these interfaces.

In Android and Kotlin, extension functions can be applied, but in pure Java, such a mechanism does not exist.

Example of using a decorator:

interface Printer {
    void print(String message);
}

class SimplePrinter implements Printer {
    public void print(String message) {
        System.out.println(message);
    }
}

class DecoratorPrinter implements Printer {
    private Printer wrapped;

    public DecoratorPrinter(Printer wrapped) {
        this.wrapped = wrapped;
    }

    public void print(String message) {
        // Add functionality
        System.out.print("[Decorated] ");
        wrapped.print(message);
    }
}

// Usage
Printer printer = new DecoratorPrinter(new SimplePrinter());
printer.print("Hello");

Thus, extending functionality is achieved by wrapping an object, not by changing the original class.