Possible Duplicate:
Interface vs Abstract Class (general OO)
Following are the confusions which I have between interface, abstract and normal class-
-
I know an abstract class can have a method with no implementation, but what is the harm in declaring method as virtual in base class with some dummy implementation and over ride in derived class. Looking for a practical scenario where answer can be validated?
-
Why we need an interface when we have abstract class, I know with interface we can have multiple inheritance, and have goggled about various theoretical reasons, looking for practical scenarios where abstract class just cant help and you have to go for interface?
-
Is having an abstract class and interface is not an overhead?
Practical Examples
I think you are thinking too hard. Its like looking at a fork and a spoon and worrying about when to use when. There is no right answer, just use the one that makes sense to you for what you are doing. Many paths to getting there.
Here is how I use these in the real world (fortune 500 companies etc…)
Interfaces allow you to add as many as you want to a class. They essentially allow you to bind to any contract as much as you want. They are as minimal as you get. An example I used this in was a music encoder service where it just had some simple properties and methods that each encoder type needed. I later added more interfaces as other requirements came into play but I didn’t want to break the code for other parts not needing to know or care about the new interface. The encoders were very loosely coupled and could have more than one contract so this made sense for me. The main thing about interfaces is when you use them, don’t keep changing them as it defeats the purpose of the interface, rather make a new one. Interfaces are the best for plugin type of development.
Abstract classes are kind of cool because you can have some base implementation already cooked in there but you are essentially saying "but you still have to make this part" as its the responsibility of the class to implement this. This could be for a "save" method for example. Let’s say you had some abstract class that handled data in the same way but you had many commonalities in the underlying abstract class that did a lot of work but you had a requirement that each inherited type save its own data in its own format needed for example. This could relate to a networked item that saved things in facebook and twitter or another item that saved things in a database and a file system but the core code always hit a central db to say it was saved with last date modified.
So sorry, I was bored, lots of typing. But that’s how I have used them.