- class Program
- { //从学生,老师,校长类中抽象出人的类,学生和老师都有收作业的方法,但是校长不会收作业。
- static void Main(string[] args)
- {
- Student s = new Student();
- s.GetHomework();
- Teacher t = new Teacher();
- t.GetHomework();
- HeadMaster hm = new HeadMaster();
- hm.GetHomework();
- Console.ReadKey();
- }
- }
- abstract class Person
- {
- public virtual void GetHomework()
- {
- Console.WriteLine("我不收作业!");
- }
- }
- class Student:Person
- {
- public override void GetHomework()
- {
- Console.WriteLine("我是学生代表,来收作业的");
- }
- }
- class Teacher : Person
- {
- public override void GetHomework()
- {
- Console.WriteLine("我是老师,我负责收学生代表送来的作业!");
- }
- }
- class HeadMaster : Person
- {
- }
复制代码 当然你可以不声明Person类为抽象类
还可以把virtual关键字改成abstract,那么就不能有方法体,等待派生类去重写 |