文档库 最新最全的文档下载
当前位置:文档库 › 3136003039曾华杰c#实验报告四

3136003039曾华杰c#实验报告四

福建农林大学计算机与信息学院实验报告

实验(四)面向对象的高级程序设计

一、实验目的和要求

1.理解类的继承性和多态性,掌握其应用方法

2.理解抽象类、接口的概念,掌握抽象类与接口的定义以及使用方法

3.区别静态类与非静态类,掌握静态字段、静态方法和静态构造函数的定

义方法

二、实验内容和原理

1. (1)建立一个Person类,该类有name和age两个成员变量

(2)为Person类编写构造函数(带两个参数,分别对应name和age)

(3)为Person类编写虚方法ShowInfo用于显示name和age

(4)建立一个Student类,其是Person类的派生类,除了继承下来的name 和age外,还有个成员变量number

(5) 编写Student类的构造函数,对name、age以及number进行初始化

(6)为Student类重写ShowInfo方法,显示name、age以及number信息(7)在Main方法中创建Student类的一个实例,显示其姓名、年龄以及学号。

2. (1)建立一个基类Shape,在该类中定义成员变量area表示形状的面积,抽象方法GetArea用于计算形状的面积,ShowArea方法用于显示形状的面积。

(2)建立Shape的一个派生类Triangle,在该类中增加成员变量bottom和high表示底和高,定义一个构造函数以便在创建实例时对其进行设置,对基类中的GetArea方法进行重写以实现对三角形面积的计算。

(3)建立Shape的一个派生类Rectangle,在该类中增加成员变量length 和width分别表示长和宽,定义一个构造函数(带长和宽两个形参),对基类中的GetArea方法进行重写以实现对矩形面积的计算。

(4)在Main方法中创建Circle和Retectangle的实例,调用各自的GetArea 方法实现对面积的计算,并调用基类的ShowArea方法实现对面积的输出。

三、实验环境

1.硬件环境:Windows操作系统

2.软件环境:Visual Studio .Net

四、算法描述及实验步骤

1.算法描述(可以用流程图、伪代码或源程序描述)

2.实验步骤

第一题:

namespace ConsoleApplication2

{

class Program

{

static void Main(string[] args)

{

Student s = new Student("曾华杰",21,39);

s.ShowInfo();

Console.ReadLine();

}

}

class Person {

protected string name;

protected int age;

public Person() { }

public Person(string name, int age) {

https://www.wendangku.net/doc/3f15586388.html, = name;

this.age = age;

}

public virtual void ShowInfo() {

Console.WriteLine("Person姓名:{0},年龄:{1}",name,age);

}

}

class Student :Person{

int number;

public Student(string name, int age, int number)

{

https://www.wendangku.net/doc/3f15586388.html, = name;

this.age = age;

this.number = number;

}

public override void ShowInfo()

{

Console.WriteLine("Student姓名:{0},年龄:{1},学号:{2}", name, age,number);

}

}

}

第二题:

namespace ConsoleApplication3

{

class Program

{

static void Main(string[] args)

{

Triangle t = new Triangle(50,20);

t.GetArea();

t.ShowArea();

Rectangle r = new Rectangle(50, 20);

r.GetArea();

r.ShowArea();

Console.ReadLine();

}

}

abstract class Shape

{

protected double area;

public abstract void GetArea();

public void ShowArea() {

Console.WriteLine("面积是:{0}",area);

}

}

class Triangle:Shape {

double bottom;

double high;

public Triangle(double bottom, double high) {

this.bottom = bottom;

this.high = high;

}

public override void GetArea() {

this.area = bottom * high / 2;

}

}

class Rectangle : Shape

{

double length;

double width;

public Rectangle(double length, double width) {

this.length = length;

this.width = width;

}

public override void GetArea()

{

this.area = length * width;

}

}

}

五、调试过程

六、实验结果

1.

2.

七、总结

相关文档
相关文档 最新文档