Answer the question
In order to leave comments, you need to log in
What is the difference between dependency injection and inheritance?
It seems that dependency injection and class extends perform the same function, getting methods and properties of a specific class. So what is the difference between them, and when and which is better to use?
Answer the question
In order to leave comments, you need to log in
To be honest, these are fundamentally different things.
There are OOP principles - inheritance, abstraction, encapsulation, polymorphism.
Inheritance:
{class} extends {superClass} is the ability of a class or object to be based on another class or object.
For example, Dog -> Animal Cat -> Animal
Dependency injection is a variation of IoC (inversion of control). For example, there is a class inside which there is an object for connecting to the database. Moreover, connection is an interface. Which implementation, depending on the database used, will be implemented during runtime is currently not defined.
UserService {
Connection connection;
}
Here, as elsewhere in OOP, the question is not technical, but rather philosophical. Your question is probably better asked as - "What is the difference between inheritance and composition, because with composition we also get access to the methods and fields of the class." The difference is that when inheriting, a class becomes a direct descendant of a certain class, when composing, this class becomes part of our class, while there are no "family ties" between them.
Well, for example, would it be logical to inherit Engine -> Car ? I don't think. But to introduce the same dependency, to make a composition of objects, to make the engine part of the machine, but not its heir - this is already logical, this is how we imagine the real world.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question