Sobes.tech
Junior — Middle

How is dependency injection implemented using a setter method in object-oriented programming?

sobes.tech AI

Answer from AI

Dependency injection via a setter method in object-oriented programming (for example, in Java) means that the object receives a reference to the dependency through a special method, usually called setDependency or similar.

Example:

public class Service {
    private Repository repository;

    // Setter for dependency injection
    public void setRepository(Repository repository) {
        this.repository = repository;
    }

    public void doWork() {
        repository.save();
    }
}

In this example, the Service object does not create the Repository itself but receives it from outside via the setter. This facilitates testing and increases code flexibility, as dependencies can be changed at runtime.

How is dependency injection implemented using a… - sobes.tech