I'm currently working on a Java project. I'm quite new to Java. I have done C++/C# in the past.
I have a question regarding dependency injection. The basic idea why to use it is already clear to me.
public class MyClass
{
@Inject
private IFoo fooInterface;
@Inject
private Bar barClass;
}
with
public interface iFoo
{
}
public class Bar
{
}
Now it makes perfectly sense to inject an actual interface implementation to reduce dependencies.
But why would I like to inject a "normal" class with does not implement an interface?
Could you help me understand?
Edit: Thank you guys for all your comments. I believe I'm getting now the idea behind dependency injection.
Just to clarify: After speaking to the other devs I was told that in our project all injected dependencies are constructed at startup. However not all member objects are already known at startup time. Therefore these members objects can't be passed via constructor.
Another point is that, for each class type (for ex. Bar) only 1 instance seams to be constructed for the whole project, this instance will be passed around in the whole project and accessed by multiple threads. Therefore we might run into concurrency issues if we use member variables.
=>the conclusion in our team was to avoid member variables and pass all arguments as function arguments.
=>Now I'm searching for a way to have DI (which makes perfectly sense) but also to have members variables.