博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

抽象类

Posted on 2007-03-20 14:52  小飞龙(Jack)  阅读(167)  评论(0编辑  收藏  举报

可以强制派生类覆盖基类的方法:将基类的方法声明为抽象的.为此,我们需要使用关键字abstract.抽象方法没有方法体,有派生类来提供.
当方法被声明为抽象的时,其所属的类也必须被声明为抽象的.
namespace ConsoleApplication1
{
    abstract class Person
    {
        protected string firstName;
        protected string lastName;

        public Person()
        {

        }
        public Person(string fn, string In)
        {
            firstName = fn;
            lastName = In;
        }
        public abstract void displayFullname();
    }
    class Employee : Person
    {
        public ushort hireYear;
       
        public Employee()
            : base()
        { }
        public Employee(string fn, string In, ushort hy)
            : base(fn, In)
        {
            hireYear = hy;
        }
        public override void displayFullname()
        {
            Console.WriteLine("Employee:{0}{1}",firstName,lastName);
        }
    }
    class Contractor : Person
    {
        public string company;
       
        public Contractor()
            : base()
        { }
        public Contractor(string fn, string In, string c)
            : base(fn, In)
        {
            company = c;
        }
        public override void displayFullname()
        {
            Console.WriteLine("Contractor:{0}{1}",firstName,lastName);
        }
    }
    class NameApp
    {
        public static void Main()
        {
            Person me = new Employee("Bradley","Jones",1983);
            Person Greg = new Contractor("Hill","Batfield","Data Diggers");

            me.displayFullname();
            Greg.displayFullname();
            Console.Read();
        }
    }
}