I
I
itfan2021-03-24 10:35:20
Java
itfan, 2021-03-24 10:35:20

Why do we need interfaces when implementing dependency injection?

I'm learning Java and got to the topic of dependency injection. I figured out what a class dependency is and what an interface is. However, they cannot understand why to use interfaces when implementing dependency injection?

Suppose there is class A and class B. To get rid of the dependency, class B does not create an object based on class A. The constructor takes an interface object. In turn, class A is an implementation of this interface, and in the main program its object is sent as an argument to the class B constructor. Why is an interface needed here? Isn't it easier to send an object right away? If you get rid of the interface, it works the same way.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
S
sanya misharin, 2021-03-24
@sanya_misharin

This is done so that your class in which you inject the dependency is not tied to the implementation.
For example, you have a class that wants to cache something, you inject a cache interface into it, but the class does not depend on which cache you will use, all this should be done in the settings, today you cache to a file, tomorrow to a radish, and so on.
This is all called polymorphism

V
Vasily Bannikov, 2021-03-24
@vabka

Yes, it is quite possible without an extra interface if this class has only one implementation.
If a class implements some kind of complex logic or has side effects, then it will be easier for tests to implement its simplified version without that code - this is what an interface is for, so that you can override

M
Mercury13, 2021-03-24
@Mercury13

If we assume that interface A has only one implementation ...
1. If object A itself refers to object B - so that these objects are not a single lump that can only be drawn into the project together.
2. To speed up recompilation when object A changes.
But an interface can have many implementations, then ...
3. To make a special version of A for unit tests of object B.
4. To make it easier to extend the code or move a module from project to project: for example, the same packer that accepts an abstract stream as input can work with files or with a network.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question