⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 9-5.cs

📁 java基础方面的一些实例代码
💻 CS
字号:
//程序9-5
using System;
namespace School
{
	public class Student // 基类
	{
		protected string studName;  // protected成员
		protected int studID;
		public Student()  // 基类的无参数构造函数
		{  }
		public Student(string str, int id) // 基类的构造函数
		{
			studName=str;
			studID=id;
		}
		public string TheName   // 属性
		{
			get { return studName;}
		}
		public void PrintBase() // 方法
		{
			Console.WriteLine("在基类: Student.");
		}
		public void FindInfo(int id) // 方法
		{
			if(id==studID)
				Console.WriteLine ("{0}is a student. ", studName);
		}
	} 
	public class CollegeStudent :Student  // 派生类
	{        
		string department;   // 新添加的成员
		public CollegeStudent(string deptmnt,string str, int id):base(str,id) // 构造函数
		{
			department=deptmnt;
		}
		public void PrintDerived() // 方法
		{
			Console.WriteLine("在派生类: CollegeStudent.");
		}
		public new void FindInfo(int id) // 方法
		{
			if(id==studID)
				Console.WriteLine ("{0}is a student in the {1} Department. ", studName,department);
		}
	}
	public class Test  // 测试
	{
		public static void DisplayCls(Student stu) // 方法
		{
			Console.WriteLine("Base or Derived class? " + stu.ToString());
		}
		public static void DisplayObj(Student stu) // 方法
		{
			Console.WriteLine("The Student Name is " + stu.TheName);
		}
		public static void Main() // Main 方法
		{
			Student StudentA = new Student("李一",0518244);
			Student StudentB = new CollegeStudent("计算机","王二",0518255); //基类的对象,引用指向派生类的空间
			Student StudentC = new Student("张三",0518266);
			Student StudentD = new CollegeStudent("计算机","刘四",0518277); //基类的对象,引用指向派生类的空间
			CollegeStudent CollegeStudentA=new CollegeStudent("计算机","赵五", 0518288);
			CollegeStudent CollegeStudentB=new CollegeStudent("计算机","陈六", 0518299);
			StudentA = CollegeStudentA;    //允许,派生类对象可以赋值基类对象
			//CollegeStudentA = StudentB;  //错误,不能将基类对象隐式转换为派生类
			//CollegeStudentA = (CollegeStudent) StudentB; //可以进行强制转换,如果转换不成功则抛出异常。
			//CollegeStudentA = StudentB as CollegeStudent;//可以进行as转换,如果转换不成功则返回null。
			DisplayObj(StudentC);
			DisplayObj(CollegeStudentB);  //形参是基类对象,实参为派生类对象
			DisplayCls(StudentC);
			DisplayCls(CollegeStudentB);  //形参是基类对象,实参为派生类对象
			CollegeStudentB = (CollegeStudent) StudentB;
			//CollegeStudentB = (CollegeStudent) StudentC;	//编译通过,运行时错误,因为引用的指向不同
			CollegeStudent CollegeStudentC;
			CollegeStudentC= StudentC as CollegeStudent; // 转换不成功,因为引用指向的空间不一致,返回null
			CollegeStudent CollegeStudentD = StudentD as CollegeStudent; // 转换成功,因为引用指向的空间是一致的
			if(CollegeStudentC==null)Console.WriteLine("CollegeStudentC is null");
			if(CollegeStudentD!=null)Console.WriteLine("CollegeStudentD is not null");
			CollegeStudentD.FindInfo(0518277);
		}
	}
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -