N
N
NarkoMan012021-05-06 12:58:14
OOP
NarkoMan01, 2021-05-06 12:58:14

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

2 answer(s)
O
Orkhan Hasanli, 2021-05-06
@NarkoMan01

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;
}

Those. if a developer wants to connect a MySQL database, then the connection implementation will be implemented to work with MySQL. For example, MySqlConnection
I.E. the UserService class does not decide which dependency should be injected there. For him, this is done by a separate mechanism according to the configuration.
I gave abstract examples so that you can better see the difference between DI & inheritance

D
DollyPapper, 2021-06-16
@DollyPapper

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 question

Ask a Question

731 491 924 answers to any question