课程名称 C#程序设计
实验名称 实验一
贰、第二题
一、实验题目
假设图书馆的图书类Book包含书名、编号、出版社、作者属性,读者类Reader包含姓名和借书证属性,每位读者最多可以借阅5本书,设计他们的公共基础类BClass。
二、实验要求
模拟3位读者,列出他们的借书情况。
三、实验代码以及执行结果
1、BClass类:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace 第二题
{
class BClass
{
private string Name; //名称
private string Id; //编号
public BClass(string Name, string Id)
{
this.Name = Name;
this.Id = Id;
}
public void show()
{
Console.Write("{0} ({1})", Name, Id);
}
}
}
2、Book类:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace 第二题
{
class Book : BClass
{
private string author; //作者
private string publishingHouse; //出版社
public Book(string bookName, string bookId, string author, string publishingHouse) : base(bookName, bookId)
{
this.publishingHouse = publishingHouse;
this.author = author;
}
public void show()
{
base.show();
Console.Write(" 作者:{0}", author);
Console.Write(" 出版社:{0}", publishingHouse);
}
}
}
3、Reader类:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace 第二题
{
class Reader : BClass
{
private Book[] borrowBooks; //所借图书对象数组
private int top; //数组的最后一个元素的指针
public Reader(string Name, string borrowCertificateId) : base(Name, borrowCertificateId)
{
borrowBooks = new Book[5];
top = 0;
}
public void rentBook(Book b)
{
borrowBooks[top] = b;
top++;
}
public void show()
{
Console.Write("读者:");
base.show();
Console.WriteLine(" 所借图书:");
for (int i = 0; i < top; i++)
{
Console.Write(" {0}:", i + 1);
borrowBooks[i].show();
Console.WriteLine();
}
}
}
}
4、主类:
using System;
namespace 第二题
{
class Program
{
static void Main(string[] args)
{
Book book1 = new Book("算法设计与分析", "102226", "李春葆","清华大学出版社");
Book book2 = new Book("计算机操作系统", "076768", "汤小丹", "西安电子科技大学出版社");
Book book3 = new Book("数据库原理与应用", "015545", "刘征海", "上海交通大学出版社");
Book book4 = new Book("程序设计语言与编译", "024426", "王晓斌","电子工业出版社");
Book book5 = new Book("C#程序设计教程", "195413", "李春葆", "清华大学出版社");
Book book6 = new Book("学术英语", "148325", "蔡基刚", "外语教学与研究出版社");
Book book7 = new Book("计算机网络", "269601", "谢希仁", "电子工业出版社");
Book book8 = new Book("UML建模、设计与分析", "330884", "夏丽华", "清华大学出版社");
Book book9 = new Book("软件设计与体系结构", "243308", "董威", "高等教育出版社");
Book book10 = new Book("软件测试方法和技术", "143037", "朱少民", "清华大学出版社");
Reader reader1 = new Reader("张三","1022");
Reader reader2 = new Reader("李四","2442");
Reader reader3 = new Reader("王五","2696");
reader1.rentBook(book1);
reader1.rentBook(book2);
reader1.rentBook(book3);
reader2.rentBook(book4);
reader2.rentBook(book5);
reader2.rentBook(book6);
reader3.rentBook(book7);
reader3.rentBook(book8);
reader3.rentBook(book9);
reader3.rentBook(book10);
reader1.show();
reader2.show();
reader3.show();
}
}
}
5、执行结果:
四、实验总结
通过这次实验,我学会了子类继承父类时,子类可以使用父类的属性和方法,并在父类的基础之上再添加自己专有的属性与方法。子类在构造自己的构造函数时还需要通过base()调用父类的构造函数,子类若想调用父类的方法同样也是通过base.show() //假设这里的show()就是父类中的方法。