Abstraction

From JholJhapata
Revision as of 03:28, 11 February 2020 by Admin (talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

Abstraction is the process representing essential features without including background details, to reduce the complexity for the users. Abstraction can be achieved with either abstract classes or interfaces.

Abstract class & Abstract method

Abstract keyword is used with classes and methods:

  • Abstract class is a restricted class that cannot be used to create objects. To access it, it must be inherited from another class.
  • Abstract method can only be used in an abstract class, and it does not have a body. The body is provided by the derived class.
   abstract class Software
   {
       // Abstract method (does not have a body)
       public abstract void addIcon();
       // Regular method
       public void defaltPath()
       {
           Console.WriteLine("c:");
       }
   }
   // Derived class (inherit from Software)
   class WinZip : Software
   {
       public override void addIcon()
       {
           // The body of addIcon() is provided here
           Console.WriteLine("Desktop");
       }
   }
   class Program
   {
       static void Main(string[] args)
       {
           WinZip myWinZip = new WinZip(); // Create a WinZip object
           myWinZip.defaltPath();  // Call the abstract method
           myWinZip.addIcon();  // Call the regular method
       }
   }

Interface

An interface is a completely "abstract class", which can only contain abstract methods and properties (with empty bodies). Interface is another way to achieve abstraction in C#.

   interface Software
   {
       // Abstract method (does not have a body)
       void addIcon();
       // Abstract method (does not have a body)
       void defaltPath();
   }
   // Derived class (inherit from Software)
   class WinZip : Software
   {
       public void addIcon()
       {
           // The body of addIcon() is provided here
           Console.WriteLine("Desktop");
       }
       public void defaltPath()
       {
           // The body of defaltPath() is provided here
           Console.WriteLine("c:");
       }
   }
   class Program
   {
       static void Main(string[] args)
       {
           WinZip myWinZip = new WinZip(); // Create a WinZip object
           myWinZip.defaltPath();  // Call the regular method
           myWinZip.addIcon();  // Call the regular method
       }
   }