一、一码当先---代码清单
抽象基类People
/// /// 抽象基类 /// public abstract class People { public string Name; public string Gender; public People(string outName, string outGender) { Name = outName; Gender = outGender; } /* 一个抽象方法,现在的人都上网,不同的人上网的目的是什么 基类的中抽象方法不用实现 */ public abstract void SearchInternet(); }派生类学生
public class Student : People { string StudentNum; /// /// base(outName,outGender)同时去初始化抽象类中的两个数据成员 /// /// /// /// public Student(string outName, string outGender, string outStuNum) : base(outName, outGender) { Name = outName; Gender = outGender; StudentNum = outStuNum; } public override void SearchInternet() { Console.WriteLine("这个人名叫" + Name + ",性别:" + Gender + ",工号:" + StudentNum + ",他上网的目的是查找习题答案\\n"); } }派生类老师
public class Teacher : People { string TeachNum; public Teacher(string outName, string outGender, string outTNum) : base(outName, outGender) { Name = outName; Gender = outGender; TeachNum = outTNum; } public override void SearchInternet() { Console.WriteLine("这个人名叫" + Name + ",性别:" + Gender + ",工号:" + TeachNum + ",他上网的目的是发布习题答案\\n"); } }测试程序段
namespace AbstractClass { class Program { enum PEOPLE { STUDENT = 1, TEACHER, EXIT } static void Main(string[] args) { int peopleObj = -1; string tmpName = ""; string tmpGender = ""; string teacherNum = ""; string studentNum = ""; bool isExit = false; Student studentA; Teacher teacherA; while (true) { Console.WriteLine("------------测试人上网的原因,超级准 ^ V ^ -------------------\\n"); Console.WriteLine("请选择你要创建的角色: \\n"); Console.WriteLine(" 1 学生\\n "); Console.WriteLine(" 2 教师\\n "); Console.WriteLine(" 3 退出\\n "); Console.WriteLine("------------------------------------------------------------------\\n"); /* C#的强大之处,判断输入是否为数字,直接有一个API!不知是好还是坏事 */ if (int.TryParse(Console.ReadLine(), out peopleObj) == false) { Console.WriteLine("输入的数字不合法!请输入整数(1~3)\\n"); Console.ReadLine(); } else { } switch (peopleObj) { case (int)PEOPLE.STUDENT: Console.WriteLine("请输入学生名字:\\n"); tmpName = Console.ReadLine().Trim(); Console.WriteLine("请输入学生性别:\\n"); tmpGender = Console.ReadLine().Trim(); Console.WriteLine("请输入学生学号:\\n"); studentNum = Console.ReadLine().Trim(); studentA = new Student(tmpName, tmpGender, studentNum); studentA.SearchInternet(); Console.ReadLine(); break; case (int)PEOPLE.TEACHER: Console.WriteLine("请输入教师名字:\\n"); tmpName = Console.ReadLine().Trim(); Console.WriteLine("请输入教师性别:\\n"); tmpGender = Console.ReadLine().Trim(); Console.WriteLine("请输入教师工号:\\n"); teacherNum = Console.ReadLine().Trim(); teacherA = new Teacher(tmpName, tmpGender, teacherNum); teacherA.SearchInternet(); Console.ReadLine(); break; case (int)PEOPLE.EXIT: isExit = true; break; default: break; } /* 控制台清屏 */ Console.Clear(); if (isExit) break; } } } }
二、码到成功---现场展示
三、码后炮---原理讲解
1、什么是抽象类?
用来作为派生类的基类,定义时使用abstract修饰,如public abstract class xxx。
2、抽象类与非抽象类的区别
(1)不能被实例化,只有通过继承它才具有生命力;
(2)可以包含抽象成员,非抽象类不能;抽象方法只能出现在抽象类中,但抽象类中的方法并不全是抽象方法,如构造函数及其它方法。
3、抽象方法
(1) 声明时使用abstract修饰;
(2)不能使用后面修饰词,virtual,private,static等;
(3)在抽象类中不提供实现
四、源码附件