2

I can't understand a simple thing. example: A is an interface, B is a class that implement correctly A. What dose exactly mean doing:

A name = new B(some_argument); 

I see lot of people using this instead of

B name = new B(some_argument); 

But I can't figure out what dose that mean making an object with an interface. And WHY they do this? There are some differences between them? Sometimes one is better than other? for example the opposite dose not work

B name = new A();

1 Answers1

2

technically both works.

The reason most people use the first solution (and you should do that too) is that an interface defines a certain contract / API for a type of classes. That means an interface is used when you dont know the implementation of it or the implementation is exchangeable.

So coding against the interface and not against the real specific implementation is the best way to make your code exchangeable and generic which helps you to modularize your code, keep hard-linked-dependency between classes as low as possible and make your code maintainable.

Also an interface can be used to add additional functionality to a class as you can implement multiple interface but only extend one class.

A practical example: Think of an SDK for a plugin. It defines some interface. How do you want to call a function of a class implementing this interface when the implementation of that interface is done by an other guy wrinting a plugin two years after you developed your application/sdk? ;)

NeoP5
  • 611
  • 7
  • 19