HI WELCOME TO SIRIS

C# Abstract

Leave a Comment
Abstract classes are the way to achieve abstraction in C#. Abstraction in C# is the process to hide the internal details and showing functionality only. Abstraction can be achieved by two ways:
  1. Abstract class
  2. Interface
Abstract class and interface both can have abstract methods which are necessary for abstraction.

Abstract Method

A method which is declared abstract and has no body is called abstract method. It can be declared inside the abstract class only. Its implementation must be provided by derived classes. For example:
  1. public abstract void draw();  

An abstract method in C# is internally a virtual method so it can be overridden by the derived class.

You can't use static and virtual modifiers in abstract method declaration.

C# Abstract class

In C#, abstract class is a class which is declared abstract. It can have abstract and non-abstract methods. It cannot be instantiated. Its implementation must be provided by derived classes. Here, derived class is forced to provide the implementation of all the abstract methods.
Let's see an example of abstract class in C# which has one abstract method draw(). Its implementation is provided by derived classes: Rectangle and Circle. Both classes have different implementation.
  1. using System;  
  2. public abstract class Shape  
  3. {  
  4.     public abstract void draw();  
  5. }  
  6. public class Rectangle : Shape  
  7. {  
  8.     public override void draw()  
  9.     {  
  10.         Console.WriteLine("drawing rectangle...");  
  11.     }  
  12. }  
  13. public class Circle : Shape  
  14. {  
  15.     public override void draw()  
  16.     {  
  17.         Console.WriteLine("drawing circle...");  
  18.     }  
  19. }  
  20. public class TestAbstract  
  21. {  
  22.     public static void Main()  
  23.     {  
  24.         Shape s;  
  25.         s = new Rectangle();  
  26.         s.draw();  
  27.         s = new Circle();  
  28.         s.draw();  
  29.     }  
  30. }  
Output:

drawing ractangle...
drawing circle...

0 comments:

Post a Comment

Note: only a member of this blog may post a comment.