When to use interfaces and when to abstract class ??
When to use interfaces and when to abstract class ??
Collapse
X
-
Tags: None
-
Abstract classes should be used for closely related objects, whereas interfaces are used for providing common functionality to unrelated classes. Use interfaces for designing small functional units. However, use abstract class if you are designing large functional units -
Hy,
An abstract class allows you to create functionality that subclasses can implement or override. An interface only allows you to define functionality, not implement it. And whereas a class can extend only one abstract class, it can take advantage of multiple interfaces.
Refer this site for more information:
Comment
-
This took me a while to wrap my head around this and ultimately I just had to write code that utilized both to figure it out.
An abstract class is an inheritance based concept. It should satisfy the "is a" rule (checkout Liskov Substitution Principle). As an example:
Code:public abstract class Dog { public abstract void Bark(); } public class Bulldog : Dog { public override void Bark() { Console.WriteLine("Woof"); } } public class Chihuahua : Dog { public override void Bark() { Console.WriteLine("yip"); } }
Interfaces are a very different construct. Interfaces guarantee that an object, whatever that object is, can perform some sort of action. A class that implements IComparable can be compared (CompareTo method). It is not an object of type "comparable ". If we implement IEnumerable our objects must create an enumerator to walk a collection. We have not created an object of type "Enumerable ". We have just guaranteed a behavior without layering on any other notions about what our object is. (Dogs could implement IComparable as could PeatMoss without any dissonance in our domain/mental model).
Abstract classes are about inheritance hierarchies and the domain model you are working in. Interfaces deal with specific, constrained behaviors you need a class to have.Comment
Comment