Abstract
The
abstract modifier can be used with classes, methods, properties,
indexers, and events.
Use
the abstract modifier in a class declaration to indicate that a class is
intended only to be a base class of other classes.
Abstract
classes have the following features: 
- An abstract class cannot be instantiated.
 - An abstract class may contain abstract methods and accessors.
 - It is not possible to modify an abstract class with the sealed modifier, which means that the class cannot be inherited.
 - A non-abstract class derived from an abstract class must include actual implementations of all inherited abstract methods and accessors.
 
Use
the abstract modifier in a method or property declaration to indicate that the
method or property does not contain implementation.
Abstract
methods have the following features: 
- An abstract method is implicitly a virtual method.
 - Abstract method declarations are only permitted in abstract classes.
 - Because an abstract method declaration provides no actual implementation, there is no method body; the method declaration simply ends with a semicolon and there are no braces ({ }) following the signature. For example:
 
·        
The
implementation is provided by an overriding
method, which is a member of a non-abstract class. 
- It is an error to use the static or virtual modifiers in an abstract method declaration.
 
public abstract void MyMethod();
An
abstract class must provide implementation for all interface members. An abstract class that implements an interface might map the interface methods onto abstract methods. For example:
interface I
{
    void M();
}
abstract class C : I
{
    public abstract void M();
}
Example
In this example, the class MyDerivedC is derived from an abstract class MyBaseC. The abstract class contains an abstract method, MyMethod(), and two abstract properties, GetX() and GetY().
// abstract_keyword.cs
// Abstract Classes
using System;
abstract class MyBaseC   // Abstract class
{
   protected int x = 100; 
   protected int y = 150;
   public abstract void
MyMethod();   //
Abstract method
   public abstract int
GetX   //
Abstract property
   {
      get;
   }
   public abstract int
GetY   //
Abstract property
   {
      get;
   }
}
class MyDerivedC: MyBaseC
{
   public override void
MyMethod() 
   {
      x++;
      y++;  
   }   
   public override int
GetX   //
overriding property
   {
      get 
      {
         return
x+10;
      }
   }
   public override int
GetY   //
overriding property
   {
      get
      {
         return
y+10;
      }
   }
   public static void Main() 
   {
      MyDerivedC
mC = new MyDerivedC();
      mC.MyMethod();
      Console.WriteLine("x = {0}, y = {1}", mC.GetX,
mC.GetY);    
   }
}
Output
x = 111, y = 161
MyBaseC mC1 = new MyBaseC();   // Error
 
you will
get the following error message:Cannot create an instance of the abstract class 'MyBaseC'.
0 comments:
Post a Comment