Monday, 27 October 2014

Abstract Class & Interface

What is an Abstract Class?

An abstract class is a special kind of class that has no implementation. It cannot be instantiated. Its implementation logic is provided by the classes that derive from it. It can have both abstract as well as non-abstract methods. 
It is not compulsory to have only abstract methods in an abstract class. We can also have an abstract class with only non-abstract methods.

Why do we need an Abstract Class?
 

With an Abstract Class, we can provide some kind of default functionality for all derived classes to extend from. This is useful to avoid code duplication in many cases. 

Suppose we are defining an iPhone class for Apple and then inheriting it to iPhone5 and iPhone5s subclasses. Practically we don't want an object of an iPhone class since we first need to know the model of iPhone. So, the iPhone class should be an abstract class that contains some predefined functions like Call() and SMS() for all iPhone models to share . We can also add abstract methods like Model() and Color() into the iPhone class that must be implemented by all the subclasses inheriting iPhone. The main advantage of this approach is, whenever we inherit the iPhone class into a derived class, say iPhone5s, we need not define the Call() and SMS() methods again. We just need to implement the abstract methods and we are good to go. It helps to provide default functionality in all the derived classes and also avoids code duplication. 

  1. -If we don't provide the definition of the abstract method in the derived class, it throws an error:
  2. -An inheritance between abstract to abstract classes is possible. We don't need to implement abstract methods of the base abstract class into a derived abstract class. We can implement it later in concrete classes. 
  3. -An abstract class can never be sealed or static. 
  4. -An abstract class can have abstract as well as non abstract methods. 
  5. -The abstract keyword can be used with class, methods, properties, indexers and events.
  6. -Abstract members can only be declared inside an abstract class. 
  7. - An abstract member cannot be static or private. 
  8. - An abstract method cannot be marked virtual. 
  9. - A concrete class cannot inherit more than one abstract class, in other words multiple Inheritance is not   possible.

Reference:
http://www.c-sharpcorner.com/UploadFile/d0e913/abstract-class-interface-two-villains-of-every-interview/



What an interface is ?

In the real world, an interface means a medium to interact with something. To be precise, it's a point where two systems, subjects, organizations and so on meet and interact. Suppose you are going for an interview of Programmer Profile. The interview is only possible if the interviewer and you speak the same language.
Moreover, you and the interviewer have the same skill set of programming languages to discuss upon.
Similarly, in the programming world, an interface means a contract to interact with multiple code modules. If a class wants to communicate with an interface, it must implement it and define its members. Consider it like the interviewer's question and you need to answer it correctly, if you want the job.

The MSDN Library defines the interface like a pure abstract class. An interface contains only the signatures of methods, properties, events, or indexers. It has no implementation of its own and can only be implemented by a class or a struct. Any of the two that implement the interface must provide the definitions to members specified in the interface. It is like a contract for all the derived classes to follow.

An interface is declared using the interface keyword. interface members are implicitly public and abstract, so we cannot prefix any access modifiers to it. An interface cannot contain fields, constant members, constructors, destructors and static members.

Why we need an interface

An interface is not a class. It contains only method signatures. It has no implementation on its own and cannot be instantiated. Its implementation logic is provided by the classes that derived from it. An interface is mostly considered to be a pure abstract class. However, there is the advantage of using an interface over an abstract class; that is "Multiple Inheritance Support". In C#, two classes (either abstract or concrete) cannot be inherited by the same derived class. It causes ambiguity in the derived class if both have the same method signature. We can do multiple inheritance in C# using interfaces.

An interface plays a vital role in the Service Oriented Architecture (SOA). In WCF, we use interfaces to define Service Contracts. A single class can implement any number of Service Contract Interfaces. It is generally accepted as the best practice to do so. However, we can also use classes for Service Contracts.

How to define an interface

Suppose we need to define a class for a Smart Phone. The class can have members like OS, AppStore and Call. The Smartphone can be either Android based or iOS based and cannot be both. There is no common functionality between an Android and iOS Smartphone, so we don't need to provide any default functionality. One approach is to make the SmartPhone class abstract and also all its members abstract. This approach works fine and several concrete classes like Samsung, Apple, HTC can inherit from it.

Now, after a few days Apple wants to add a Touch ID feature to its Smartphone. You can add TouchID as an abstract method in your abstract base class SmartPhone. But what if HTC doesn't want that feature and neither does Samsung? So, the TouchID method cannot be placed inside the abstract class SmartPhone. An alternative is to define another abstract class Features and add the TouchID method to it. This is also a bad idea since C# doesn't support inheritance of multiple classes (abstract or concrete) into a derived class.

In this situation, an interface is useful and plays a vital role in solving the problem. An interface provides only the method definitions, just like an abstract class, but can be useful in multiple inheritances. You can make the Features class an interface and add the TouchID method to it. It provides only the method signature and whichever class inherits it can implement it in its own way. It is also completely valid for a class to inherit more than one interface in C#. Also, we can make the SmartPhone class an interface instead of an abstract class. It is better instead of making a pure abstract class, we can use interfaces. 
Let us consider the example discussed above and create a Console Application for it. Open Visual Studio and add a new console project as "InterfaceDemo".

Let's create an abstract class SmartPhone and define OS and AppStore abstract methods in it. We can create an abstract class by putting the keyword "abstract" before a class definition.


Now define the concrete classes Apple and Samsung that inherits from Smartphone and provides the definitions to the abstract methods OS and AppStore.

using System;  
namespace InterfaceDemo   
{   
      //Abstract Class SmartPhone with only abstract methods in it   
      abstract class SmartPhone   
      {  
         public abstract void OS();  
         public abstract void AppStore();   
      }  
      class Apple : SmartPhone   
      {  
          public override void OS()   
          {   
            //Some Implementation Here   
          }  
  
          public override void AppStore()   
          {  
             //Some Implementation Here   
          }   
       }   
  
       class Samsung: SmartPhone   
       {  
          public override void OS()   
          {   
              //Some Implementation Here   
          }  
  
          public override void AppStore()   
          {  
              //Some Implementation Here   
          }  
       }  
      
       class Program   
       {   
          static void Main(string[] args)   
          {   
          }   
       }   
}  

If we compile the code now, it works fine. Our SmartPhone class is implemented by two different concrete classes Apple and Samsung and defined depending on them. Now, let us suppose Apple wants to provide TouchID features to its Smartphone. We can add another abstract method TouchID in the SmartPhone class and let Apple inherit it and implement it. 

using System;    
namespace InterfaceDemo   
{   
    //Abstract Class SmartPhone  
    abstract class SmartPhone   
    {   
       public abstract void OS();   
       public abstract void AppStore();   
  
       //TouchID method meant only for Apple Class  
       public abstract void TouchID();   
    }   
  
    class Apple : SmartPhone   
    {   
         public override void OS()   
         {  
            //Some Implementation Here   
         }  
  
         public override void AppStore()   
         {   
             //Some Implementation Here   
         }  
  
         //Implementing the TouchID feature   
        public override void TouchID()   
        {   
            //Some Implementation Here   
        }    
    }   
  
    class Samsung: SmartPhone   
    {   
        public override void OS()   
        {   
             //Some Implementation Here   
        }  
  
        public override void AppStore()   
        {   
              //Some Implementation Here   
        }   
    }  
  
    class Program   
    {   
       static void Main(string[] args) { }   
    }  
}  

The Apple class inherits the TouchID method and provides a definition to it. Let's compile the code now and see what happens. 






It throws an error saying that the Samsung class doesn't implement the TouchID method. By the definition of abstract class, any class implements it must provide definitions to all its abstract members. The TouchID method is meant only for the Apple class and the Samsung class doesn't want to implement it. It clearly seems that our approach is wrong since the TouchID method cannot be placed in the SmartPhone abstract class. 

An alternative approach is to define another abstract class Features and define the TouchID method to it. This approach seems fine since whatever class inherits Features can implement the TouchID method. 

using System;   
namespace InterfaceDemo   
{   
      //Abstract Class SmartPhone   
      abstract class SmartPhone   
      {  
         public abstract void OS();  
         public abstract void AppStore();   
      }  
  
      //Abstract Class Features for TouchID method  
      abstract class Features   
      {  
         public abstract void TouchID();   
      }   
  
     //Apple Class inherits both SmartPhone and Features  
      class Apple : SmartPhone, Features   
      {  
         public override void OS()  
         {   
            //Some Implementation Here   
         }  
          
         public override void AppStore()   
         {  
             //Some Implementation Here   
         }  
  
         //Implementation of TouchID method in Apple Class   
         public override void TouchID()   
         {  
             //Some Implementation Here   
         }  
      }  
  
      class Samsung : SmartPhone   
      {  
         public override void OS()   
         {   
           //Some Implementation Here   
         }   
  
         public override void AppStore()  
         {  
            //Some Implementation Here   
         }   
       }  
  
       class Program   
      {  
          static void Main(string[] args)   
          {  
          }   
      }   
}

Let's compile the code and see what happens. 


It again throws an error saying we cannot have multiple base classes in a derived class. This is called Multiple Inheritance of classes and is not allowed in C#. So, our second approach also fails to implement the TouchID method. This is where an interface is useful and helps to solve the "Multiple Inheritance" issue in C#. We can define both the SmartPhone and Features as interfaces and let the classes implement them as they need to. We can also have more than one interface in a class. This is the only way to do multiple inheritance in C#. 

Let's re-create the same project using interfaces. We can create an interface using the keyword interface. It is considered a good practice to prefix "I" before the interface name, however the point is arguable and the choice is yours.
 

using System;   
namespace InterfaceDemo   
{  
     interface ISmartPhone       //Definition of Interface   
     {   
         public void OS();   
         public void AppStore();   
     }   
  
     class Program   
     {    
        static void Main(string[] args)   
        {   
        }   
     }   
}

We have defined the interface ISmartPhone with the method signatures OS and AppStore in it. If we compile the code now, it throws an error straightaway. 


It says we cannot prefix public modifiers with method signatures. In fact, no access modifier is allowed with interface methods. Interface methods are implicitly public in C# because an interface is a contract meant to be used by other classes. Moreover, we must declare these methods as public in derived classes, when we provide implementations to these methods. Also, we cannot declare these methods as static.

  1. - An important point that should be noted here is that whenever we implement interface members in derived classes, the access modifier must always be public otherwise it throws an error. If we write a protected modifier instead of public to the OS method, the compiler throws an error.


Now if the Apple class wants to implement TouchID features, it can easily be done by defining another interface IFeatures. The Apple class can simply inherit the interface and implement the TouchID functionality to its class. This is the case where an interface is useful instead of an abstract class.  

So, this way we can get multiple inheritance in C#. Let's create the objects of the concrete classes Apple and Samsung and build the project.

using System;    
namespace InterfaceDemo   
{   
     interface ISmartPhone    
     {   
         void OS();   
         void AppStore();   
     }   
  
     //New Interface meant only for Apple Class   
     interface IFeatures   
     {   
          void TouchID();  
     }  
  
     class Apple: ISmartPhone, IFeatures   
     {   
         //OS Method Implementation   
         public void OS()   
         {   
             Console.WriteLine("OS Method: The OS of this smartphone is iOS8");   
         }   
  
         //AppStore Method Implementation   
         public void AppStore()   
         {   
            Console.WriteLine("AppStore Method: The Application Store of this smartphone is iTunes");   
         }  
  
         //TouchID Method Implementation   
         public void TouchID()   
         {  
            Console.WriteLine("TouchID Method: This method provides Touch/Gesture Control features.");   
         }  
     }   
  
     class Samsung : ISmartPhone   
     {   
         //OS Method Implementation   
         public void OS()    
         {   
            Console.WriteLine("OS Method: The OS of this smartphone is Android");   
         }   
  
         //AppStore Method Implementation   
         public void AppStore()   
         {   
            Console.WriteLine("AppStore Method: The Application Store of this smartphone is Google Play");   
         }   
      }   
  
      class Program   
      {   
          static void Main(string[] args)   
         {   
             Console.WriteLine("////// - Interface Demo -////// \n");                      
             Console.WriteLine("Apple SmartPhone:");   
             Apple apple = new Apple();   
             apple.OS();   
             apple.AppStore();   
             apple.TouchID();   
               
            Console.WriteLine("\n\n");   
            Console.WriteLine("Samsung SmartPhone:");   
            Samsung samsung = new Samsung();   
            samsung.OS();   
            samsung.AppStore();   
            Console.ReadKey(); }  
      }   
}

If we run the code now, it works perfectly.  


Reference: http://www.c-sharpcorner.com/UploadFile/d0e913/abstract-class-interface-two-villains-of-every-interview756/ 

0 comments:

Post a Comment

Topics

ADO .Net (2) Ajax (1) Angular Js (17) Angular2 (24) ASP .Net (14) Azure (1) Breeze.js (1) C# (49) CloudComputing (1) CMS (1) CSS (2) Design_Pattern (3) DI (3) Dotnet (21) Entity Framework (3) ExpressJS (4) Html (3) IIS (1) Javascript (6) Jquery (9) Lamda (3) Linq (11) Mongodb (1) MVC (48) NodeJS (7) RDLC (1) Report (1) Sql Server (29) SSIS (3) SSRS (2) UI (1) WCF (12) Web Api (10) Web Service (1) XMl (1)