All about abstract classes.

转载 2006年06月16日 14:43:00

Introduction

Abstract classes are one of the essential behaviors provided by .NET. Commonly, you would like to make classes that only represent base classes, and don’t want anyone to create objects of these class types. You can make use of abstract classes to implement such functionality in C# using the modifier 'abstract'.

An abstract class means that, no object of this class can be instantiated, but can make derivations of this.

An example of an abstract class declaration is:

abstract class absClass
{
}

An abstract class can contain either abstract methods or non abstract methods. Abstract members do not have any implementation in the abstract class, but the same has to be provided in its derived class.

An example of an abstract method:

abstract class absClass
{
  public abstract void abstractMethod();
}

Also, note that an abstract class does not mean that it should contain abstract members. Even we can have an abstract class only with non abstract members. For example:

abstract class absClass
{
    public void NonAbstractMethod()
    {
        Console.WriteLine("NonAbstract Method");
    }
}

A sample program that explains abstract classes:

using System;

namespace abstractSample
{
      //Creating an Abstract Class
      abstract class absClass
      {
            //A Non abstract method
            public int AddTwoNumbers(int Num1, int Num2)
            {
                return Num1 + Num2;
            }

            //An abstract method, to be
            //overridden in derived class
            public abstract int MultiplyTwoNumbers(int Num1, int Num2);
      }

      //A Child Class of absClass
      class absDerived:absClass
      {
            [STAThread]
            static void Main(string[] args)
            {
               //You can create an
               //instance of the derived class

               absDerived calculate = new absDerived();
               int added = calculate.AddTwoNumbers(10,20);
               int multiplied = calculate.MultiplyTwoNumbers(10,20);
               Console.WriteLine("Added : {0}, 
                       Multiplied : {1}", added, multiplied);
            }

            //using override keyword,
            //implementing the abstract method
            //MultiplyTwoNumbers
            public override int MultiplyTwoNumbers(int Num1, int Num2)
            {
                return Num1 * Num2;
            }
      }
}

In the above sample, you can see that the abstract class absClass contains two methods AddTwoNumbers and MultiplyTwoNumbers. AddTwoNumbers is a non-abstract method which contains implementation and MultiplyTwoNumbers is an abstract method that does not contain implementation.

The class absDerived is derived from absClass and the MultiplyTwoNumbers is implemented on absDerived. Within the Main, an instance (calculate) of the absDerived is created, and calls AddTwoNumbers and MultiplyTwoNumbers. You can derive an abstract class from another abstract class. In that case, in the child class it is optional to make the implementation of the abstract methods of the parent class.

Example

//Abstract Class1
abstract class absClass1
{
    public abstract int AddTwoNumbers(int Num1, int Num2);
    public abstract int MultiplyTwoNumbers(int Num1, int Num2);
}

//Abstract Class2
abstract class absClass2:absClass1
{
    //Implementing AddTwoNumbers
    public override int AddTwoNumbers(int Num1, int Num2)
    {
        return Num1+Num2;
    }
}

//Derived class from absClass2
class absDerived:absClass2
{
    //Implementing MultiplyTwoNumbers
    public override int MultiplyTwoNumbers(int Num1, int Num2)
    {
        return Num1*Num2;
    }
}

In the above example, absClass1 contains two abstract methods AddTwoNumbers and MultiplyTwoNumbers. The AddTwoNumbers is implemented in the derived class absClass2. The class absDerived is derived from absClass2 and the MultiplyTwoNumbers is implemented there.

Abstract properties

Following is an example of implementing abstract properties in a class.

//Abstract Class with abstract properties
abstract class absClass
{
    protected int myNumber;
    public abstract int numbers
    {
        get;
        set;
    }
}

class absDerived:absClass
{
    //Implementing abstract properties
    public override int numbers
    {
        get
        {
            return myNumber;
        }
        set
        {
            myNumber = value;
        }
    }
}

In the above example, there is a protected member declared in the abstract class. The get/set properties for the member variable myNumber is defined in the derived class absDerived.

Important rules applied to abstract classes

An abstract class cannot be a sealed class. I.e. the following declaration is incorrect.

//Incorrect
abstract sealed class absClass
{
}

Declaration of abstract methods are only allowed in abstract classes.

An abstract method cannot be private.

//Incorrect
private abstract int MultiplyTwoNumbers();

The access modifier of the abstract method should be same in both the abstract class and its derived class. If you declare an abstract method as protected, it should be protected in its derived class. Otherwise, the compiler will raise an error.

An abstract method cannot have the modifier virtual. Because an abstract method is implicitly virtual.

//Incorrect
public abstract virtual int MultiplyTwoNumbers();

An abstract member cannot be static.

//Incorrect
publpublic abstract static int MultiplyTwoNumbers();

Abstract class vs. Interface

An abstract class can have abstract members as well non abstract members. But in an interface all the members are implicitly abstract and all the members of the interface must override to its derived class.

An example of interface:

interface iSampleInterface
{
  //All methods are automaticall abstract
  int AddNumbers(int Num1, int Num2);
  int MultiplyNumbers(int Num1, int Num2);
}

Defining an abstract class with abstract members has the same effect to defining an interface.

The members of the interface are public with no implementation. Abstract classes can have protected parts, static methods, etc.

A class can inherit one or more interfaces, but only one abstract class.

Abstract classes can add more functionality without destroying the child classes that were using the old version. In an interface, creation of additional functions will have an effect on its child classes, due to the necessary implementation of interface methods to classes.

The selection of interface or abstract class depends on the need and design of your project. You can make an abstract class, interface or combination of both depending on your needs.

All about abstract classes

http://www.codeproject.com/Articles/6118/All-about-abstract-classes Introduction Abstract ...
  • zhleiyang
  • zhleiyang
  • 2012年04月19日 13:06
  • 306

All about "about face"

上学的时候,整天去淘打口带,面对着一堆认不出名字,没有任何可供参考的信息的磁带,作出选择是一件很有趣的体验。期望找到足够的参考信息再作取舍是不太现实的,一是未必找得到,特别对于我这样英语差的人更是如此...
  • asj
  • asj
  • 2004年12月21日 21:29
  • 1211

abstract的methods不能以private修饰(Java)

有如下错误代码:abstract class Something { private abstract String doSomething (); } 解析: abstract的methods...
  • hengbao4
  • hengbao4
  • 2016年09月11日 19:21
  • 877

文件和I/O流

1.File的用于创建目录、用于表示目录、用于创建文件、用于表示文件和用于删除文件或目录。 2.字符流:abstract class Reader和Writer操作的是文本文件 3.缓冲字符流(B...
  • u011018979
  • u011018979
  • 2014年05月02日 12:20
  • 1700

Codeforces Round #371 (Div. 2) C. Sonya and Queries (01trie树)

分析:一看奇偶相互间隔,01trie树直接上,然后调试了整场…….最后Xcode单步调试才查出一个语句顺序错误,还是思维模型不真实。调试好之后只有30s提交wa5,然后发现数据是long long急...
  • jibancanyang
  • jibancanyang
  • 2016年09月14日 12:48
  • 209

[ERR] Not all 16384 slots are covered by nodes.

早些时间公司redis集群环境的某台机子冗机了,同时还导致了部分slot数据分片丢失; 在用check检查集群运行状态时,遇到错误; [root@node01 src]# ./redis-trib....
  • vtopqx
  • vtopqx
  • 2015年12月09日 14:31
  • 42068

Android Proguard 简单学习

* 配置签名信息 * 配置ProGuard 在ProGuard中添加proguard.config=proguard.cfg 运行混淆器之后输出的文件有: dump.txt    描述.a...
  • love_world_
  • love_world_
  • 2013年12月29日 21:01
  • 3251

Codeforces Round #371 (Div. 2)C. Sonya and Queries【字典树】

C. Sonya and Queries time limit per test 1 second memory limit per test 256 megabytes input st...
  • R1986799047
  • R1986799047
  • 2016年09月17日 18:53
  • 223

About Abstract Methods and Classes

this piece of writing is reprinted from the following URL: http://download.oracle.com/javase/tutori...
  • lihongye_10
  • lihongye_10
  • 2011年08月16日 00:01
  • 277

CodeForces 713A|Sonya and Queries|字典树|没方法

给出一些数字,询问一些满足对应位为偶数(0表示)或奇数(1表示)的数字的个数。 比如010格式的数字可以有818,52,98,2212等。首先各位数具体为多少并没有什么关系,所以全都模2,将长度扩展...
  • huanghongxun
  • huanghongxun
  • 2016年09月22日 22:23
  • 374
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:All about abstract classes.
举报原因:
原因补充:

(最多只允许输入30个字)