Sobes.tech
Junior — Middle

What are the ways to implement code reuse besides inheritance?

sobes.tech AI

Answer from AI

In addition to inheritance, code reuse in Java can be implemented in the following ways:

  • Composition — including objects of other classes as fields and delegating tasks to them. Allows flexible behavior combination.
  • Interfaces with default methods (since Java 8) — allow defining method implementations in interfaces that can be reused.
  • Utility classes and static methods — common functionality is placed in separate classes with static methods.
  • Design patterns — such as strategy, decorator, adapter, help reuse and extend behavior without inheritance.

Example of composition:

class Engine {
    void start() { System.out.println("Engine started"); }
}

class Car {
    private Engine engine = new Engine();
    void start() {
        engine.start();
        System.out.println("Car started");
    }
}