When talking about dependency injection, I'd usually say that classes, not objects have dependencies.
Class A
has a dependency on class B
if it requires that class B
exists and possibly works in a certain way. For example, if class A
has a call to new B()
, it has a dependency on class B
. If class B
were to disappear or change, your class A
may break.
You can in some languages break dependencies by allowing the class to depend on an interface
instead. If you depend on interface I
instead and B
implements I
, B can go away and be replaced by C
that also implements I
, and A
wouldn't need to change at all. As an example here, you could take a driver in an operating system, if you replace the disk you may get a new driver that implements the "disk drive" interface, but your operating system still talks to the disk in the same way without knowing exactly what type of disk it is.
Dependency injection is about letting you depend on interfaces instead of classes, basically instead of saying new B()
, you'll just declare that you want an object that implements I
and a suitable implementation will be injected for you. Your class A
doesn't have to have any idea that class B
or C
even exist.