Tuesday, 8 May 2012

Abstract Classes vs Interfaces

Abstract Classes    vs Interfaces
Abstract classes is a class cannot be instantiated & must be implement by sub classes. 
   1) Class can have some methods are implemented
   2) Class can have some methods are abstract
   3)  Class can have some methods implemented & remaining are abstract .

A concrete class can inherit only one Abstract class. (Because .NET programming languages doesn't support multiple inheritance).

               Its a contract all methods are virtual. No Implementation provided.  
A class must implement all methods.

Once Interface published, User cannot change it. i.e adding new methods/deleting methods/modifying  existing method signatures.  Its like a blackbox. 

A class can implement multiple interfaces. A class cannot implement multiple classes.

Interfaces share common functionality among classes. Interfaces are generic. 
Abstract classes are not , This is specific to context/concept.

Any method  accepts  interface as a param, the class(es) implemented those interfaces can be passed as an argument.  Its up-to the programmer to cast it to appropriate type.

Any method accepts abstract class as an argument, any derived class can be passed as an argument.

So Abstract classes support versioning ,because user can add new method implementations without breaking the clients. This  is not possible with interfaces, in this case new interface should be created/derived from existing interface.

  abstract  class   Machine
            void method1()
      abstract void Method2();

interface ICal
          long Add(long a,long b);
          long Sub(long a,long b);
          long Mul(long a,long b);
          long Div(long a,long b);

Abstract classes only contain abstract methods and abstract properties.
Interfaces can contain methods, properties, events or indexers.