一个完整的例子:
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication1
{
///<summary>
/// 接口的例子,接口是顶层设计//
///</summary>
interface IAnimal //顶层接口
{
void eating();
//接口中声明的方法,这里不可以用static,abstract修饰
}
abstract class Bird :IAnimal //抽象类Bird继承了IAnimal接口
{
public void eating() { Console.WriteLine("会吃!"); } //抽象类实现了接口的方法,且必须实现该方法
abstract public void flying(); //抽象类自己又定义了一个抽象方法
}
class Chick : Bird //Chick类是抽象类Bird的派生类
{
public int chibangnumber;
public Chick()
{
Console.WriteLine("这是一个小鸡!");
chibangnumber = 2;
}
//实现了抽象类的flying方法,用override
public override void flying()
{ Console.WriteLine("会飞行!"); }
};
///<summary>
/// 多层次抽象类的例子,包含三层关系,抽象类A,抽象类B继承抽象类A,类C继承抽象类B
/// 例子中的抽象类既包含抽象方法,也包含普通成员,还有构造函数
///</summary>
abstract class A //抽象类A的声明
{
public int x; //普通公有成员
public A(int m) { x = m; } //抽象类A的构造函数
abstract public int fun1(); //抽象方法fun1()声明
}
abstract class B : A //类B仍是抽象类
{
public B(int m):base(1) { x = m; } //抽象类A的构造函数
abstract public int fun2(); //增加了一个抽象方法fun2()
public abstract int px { get;set; } //定义抽象属性px,可读可写
public abstract int py { get; } //定义抽象属性py,只读
}
class C: B //类C,继承于抽象类B,必须实现所有的抽象方法
{
int y, z;
public C(int x1, int y1):base(x1) //构造函数
{ y = x1; z = y1; }
public override int fun1() //抽象方法fun1实现
{ return x * y; }
public override int fun2() //抽象方法fun2实现
{ return x / y; }
public override int px //抽象属性px的实现
{
get
{
try { return x+10; }
catch {throw new Exception("The method or operation is not implemented."); }
}
set
{ try { x = value; }
catch { throw new Exception("The method or operation is not implemented."); }
}
}
public override int py //抽象属性py的实现
{
get
{ try { return y-10; }
catch{ throw new Exception("The method or operation is not implemented."); }
}
}
}
class Program //主程序
{
static void Main(string[] args)
{
//类的使用
Chick ch = new Chick();
ch.eating();
ch.flying();
Console.WriteLine("翅膀个数是:{0}", ch.chibangnumber);
//多层次抽象类举例
C c = new C(5,2); //创建类c的对象C
Console.WriteLine("{0},{1}", c.fun1(),c.fun2());
Console.WriteLine("{0}", c.x);
Console.WriteLine("{0},{1}", c.px,c.py); //调用抽象属性
}
}
}
运行结果:
这是一个小鸡!
会吃!
会飞行!
翅膀个数是2
25,1
5
15,-5