金陵科技学院实验报告
实验项目名称: 继承与多态 实验学时: 6 同组学生姓名: 实验地点: 1318 实验日期: 11月16日-11月30日 实验成绩: 批改教师: 批改时间:
24
金陵科技学院实验报告
实验3 继承与多态
一、实验目的、要求
(1)掌握类的继承性与多态性;
(2)掌握虚方法的定义以及如何使用虚方法实现多态; (3)掌握抽象类的定义以及如何使用抽象方法实现多态; 二、实验要求
(1)编写程序要规范、正确,上机调试过程和结果要有记录; (2)做完实验后给出本实验的实验报告。 三、实验设备、环境
安装有Visual Studio .NET软件。 四、实验步骤
1、分析题意;
2、根据题目要求,新建项目; 3、编写并输入相关的程序代码; 5、运行与调试项目; 6、保存项目。 五、实验内容
1、设计一个Windows应用程序,在该程序中首先构造一个学生基本类,再分别构造小学生、中学生、大学生派生类,当输入相关数据,单击不用的按钮时,将分别创建不同的学生类对象,并输出当前学生的总人数,该学生的姓名,学生类型,平均成绩。
Student类: using System;
using System.Collections.Generic; using System.Text; namespace Test3_1 {
public abstract class Student {
protected string name; protected int age; public static int number;
public Student(string name, int age) {
this.name = name; this.age = age;
25
金陵科技学院实验报告
number++; }
public string Name {
get { return name; } }
public abstract double Average(); }
public class Pupil : Student {
protected double chinese; protected double math;
public Pupil(string name, int age, double chinese, double math) : base(name, age) {
this.chinese = chinese; this.math = math; }
public override double Average() {
return (chinese + math) / 2; } }
public class Middle : Student {
protected double chinese; protected double math; protected double english;
public Middle(string name, int age, double chinese, double math, double english)
: base(name, age) {
this.chinese = chinese; this.math = math;
26
金陵科技学院实验报告
this.english = english; }
public override double Average() {
return (chinese + math + english) / 3; } }
public class College : Student {
protected double required; protected double elective;
public College(string name, int age, double required, double elective) : base(name, age) {
this.required = required; this.elective = elective; }
public override double Average() {
return (required + elective) / 2; } } }
Form窗体内的代码:
using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text;
using System.Windows.Forms; namespace Test3_1 {
public partial class Form1 : Form {
27
金陵科技学院实验报告
public Form1() {
InitializeComponent(); }
private void btnSmall_Click(object sender, EventArgs e) { Pupil
),Convert.ToDouble(txtMath.Text));
lblShow.Text += \总人数:\+Convert.ToString( Student.number) + \姓名:\小学生\平均成绩为:\+\
}
private void btnMiddle_Click(object sender, EventArgs e) {
Middle Convert.ToInt32(txtAge.Text),
m
=
new
Middle(txtName.Text,
Convert.ToDouble(txtChinese.Text), p
=
new
Pupil(txtName.Text,Convert.ToInt32(txtAge.Text),Convert.ToDouble(txtChinese.Text
Convert.ToDouble(txtMath.Text),Convert.ToDouble(TxtEnglish.Text));
lblShow.Text += \总人数:\+ Convert.ToString(Student.number) + \姓名:\中学生\平均成绩为:\\
}
private void btnBig_Click(object sender, EventArgs e) {
College Convert.ToInt32(txtAge.Text), Convert.ToDouble(txtMath.Text));
lblShow.Text += \总人数:\+ Convert.ToString(Student.number) + \姓名:\大学生\平均成绩为:\\
} }
c
=
new
College(txtName.Text,
Convert.ToDouble(txtChinese.Text),
28