Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the need to introduce interfaces, when we already have its super-set abstract classes?

Abstract classes contains both types of methods - abstract (non-implemented) as well as concrete (implemented) methods. While interfaces contain only non-implemented methods. It means interfaces are subset of abstract classes. Then why the interfaces was introduced in C# (.Net)? According to me, there are two reasons for it:

  1. To support multiple inheritance
  2. To support inheritance for value types (structs) in C#.

Is there any other reason or some hidden concept which I am missing?

like image 494
Manish Dubey Avatar asked Mar 29 '14 15:03

Manish Dubey


1 Answers

What you're missing is considering the relationship between the two classes.

Inheritance (which you use with abstract classes) is an is-a relationship. So if you were developing an application for a vet clinic you might create an Animal abstract class and then create Cat, Dog, Bird, and Fish from that, because Cat is-a Animal, Dog is-a Animal, etc.

Interface implementation defines a can-do relationship. Perhaps you want to be able to Print several things in your application (Invoice, Animal, CustomerProfile). You shouldn't use inheritance (i.e. abstract class) for that because Invoice is-a Print doesn't make any sense, however Invoice can-do Print, CustomerProfile can-do Print does make sense.

like image 60
Craig W. Avatar answered Sep 23 '22 18:09

Craig W.