abstract class in c#

By | February 13, 2019

Abstract class in c# -: This is a type of class in c# language.An abstract class provides a partial implementation that other classes can build on. When a class is declared as abstract, it means that the class can contain incomplete members that must be implemented in derived classes, in addition to normal class members.

Abstract Members-: Any member that requires a body can be declared abstract—such as methods, properties, and indexers. These members are then left unimplemented and only specify their signatures, while their bodies are replaced with semicolons.

abstract class Shape
{
  // Abstract method
  public abstract int GetArea();
  // Abstract property
  public abstract int area { get; set; }
  // Abstract indexer
  public abstract int this[int index] { get; set; }
  // Abstract event
  public delegate void MyDelegate();
  public abstract event MyDelegate MyEvent;
  // Abstract class
  public abstract class InnerShape {};
}

Abstract Classes and Interfaces-: Abstract classes are similar to interfaces in many ways. Both are  define member signatures that deriving classes must implement, yet neither one of them can be instantiated. The key differences are first that the abstract class can contain non-abstract members, while the interface cannot. And second class can implement any number of interfaces but only inherit from one class, abstract or not.

// Defines default functionality and definitions
abstract class Shape
{
  public int x = 100, y = 100;
  public abstract int GetArea();
}
class Rectangle : Shape {} // class is a Shape
// Defines an interface or a specific functionality
interface IComparable
{
  int Compare(object o);
}
class MyClass : IComparable {} // class can be compared

An abstract class, just like a non-abstract class, can extend one base class and implement any number of interfaces. An interface, however, cannot inherit from a class. It can inherit from another interface, which effectively combines the two interfaces into one.

Example of abstract class-:

using System;  
public abstract class Shape  
{  
    public abstract void draw();  
}  
public class Rectangle : Shape  
{  
    public override void draw()  
    {  
        Console.WriteLine("computer and internet");  
    }  
}  
public class Circle : Shape  
{  
    public override void draw()  
    {  
        Console.WriteLine("netnic is best computer application");  
    }  
}  
public class TestAbstract  
{  
    public static void Main()  
    {  
        Shape s;  
        s = new Rectangle();  
        s.draw();  
        s = new Circle();  
        s.draw();  
    }  
}

The Output of This Programme

computer and internet
netnic is best computer application

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *