I have a query related to object oriented programming. I want to know when exactly do i need to use an interface and when do i have to use an abstract class? It would be great if anybody could explain it with a real world example.
Thanks!
I have a query related to object oriented programming. I want to know when exactly do i need to use an interface and when do i have to use an abstract class? It would be great if anybody could explain it with a real world example.
Thanks!
The way of choosing absract class and interface is actualy depend on the requirement. When you want to have a feature which 'can be(say optional)' part of a class/classes then it is wise to choose the interface. But when you have a feature which 'should be(a must)' part of the class it should be from an absract class.
For example : lets consider you are creating a class CAR, which should have a feature 'Tires' and without this property the CAR or any other type of vehicle cannot be complete then the feature of 'Tires' should be made inside absract base class(lets say 'Vehicle').
But consider a property/feature which is optional like a 'Convertible' can be made as an interface IConvertible.Because it is optional to any child vehicle to have this feature.
Now being this said, any class like CAR, BIKE which should be deriving from the abstract class vehicle to get the features of vehicle(Tires), at the same time only CAR can derive from IConvertible because only car can have that feature.
Choosing interface also gives you an advantage of plugin that feature to a class which you want to make IConvertible by Inheriting from it, allowed with the multiple inheritance like in .net
Hope this helps....