Answer the question
In order to leave comments, you need to log in
Why use an interface as a variable type?
Guys, help me out!
When studying design patterns, I repeatedly come across when in code examples in listings an interface is used as some types of variables (objects-instances of classes that implement this interface.) Tell me, what are the advantages of this approach, what does it give, how is it used in practice? Why is it not possible to specify just a class that implements this interface as a variable type?
I understand that this somehow expands the possibilities, but how? Probably a stupid question, but still.
Answer the question
In order to leave comments, you need to log in
Read about dependency injection.
An interface makes it possible to use all the classes that implement it without changing the code of the class where subclasses of this interface are used (it sounds crooked, but get a grasp :) )
And the essence of patterns in a nutshell is to minimize the number of changes to existing code when adding new functionality.
Read more about SOLID principles, it will also be useful.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question