金陵科技学院实验报告
}
2、设计一个Windows应用程序,在该程序中定义平面图形抽象类和派生类圆,矩形和三角形。
Figure类代码: using System;
using System.Collections.Generic; using System.Text; namespace Test3_2 {
public abstract class Figure {
public abstract double Area(); }
public class Circle:Figure {
double radius; public Circle(double r) {
radius = r; }
public override double Area() {
return radius * radius * 3.14; } }
public class JUxing:Figure {
double chang; double kuan;
public JUxing(double c, double k) {
this.chang = c; this.kuan = k; }
29
金陵科技学院实验报告
public override double Area() {
return chang * kuan; } }
public class San:Figure {
double bian; double heigth;
public San(double b, double h) {
this.bian = b; this.heigth = h; }
public override double Area() {
return bian * heigth / 2; } } }
Form窗体代码: using System;
using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text;
using System.Windows.Forms; namespace Test3_2 {
public partial class Form1 : Form {
public Form1() {
30
金陵科技学院实验报告
InitializeComponent(); }
private void btnCircle_Click(object sender, EventArgs e) {
Circle c=new Circle(Convert.ToInt32(TxtChang.Text)); lblShow.Text = \圆的面积为:\ }
private void btnJu_Click(object sender, EventArgs e) {
JUxing
j
=
new
JUxing(Convert.ToInt32(TxtChang.Text),Convert.ToInt32(TxtHigh.Text));
lblShow.Text = \矩形的面积为:\ }
private void btnSan_Click(object sender, EventArgs e) { San
s
=
new
San(Convert.ToInt32(TxtChang.Text),
Convert.ToInt32(TxtHigh.Text));
lblShow.Text = \三角形的面积为:\ } } }
3、定义一个Person类,包含姓名字段和一个方法,早上8:30学生开始上课,教师开始讲课。分别用new关键字,虚方法,抽象类实现多态性。
New关键字: using System;
using System.Collections.Generic; using System.Text;
namespace third.three {
class Program {
static void Main(string[] args)
31
金陵科技学院实验报告
{
Student s=new Student(\学生\ Teacher t=new Teacher(\教师\ Console.WriteLine(s.name+s.work()); Console.WriteLine(t.name+t.work()); Console.ReadLine(); } }
public class Person {
public string name; public interface method { string work();} }
public class Student:Person {
public Student(string name) { this.name = name; } public string work()
{ return \早上8:30开始上课\ }
public class Teacher:Person {
public Teacher (string name) { this.name = name; } public string work() { return \开始讲课\ } } 虚方法: using System;
using System.Collections.Generic; using System.Text;
32
金陵科技学院实验报告
namespace third.three.two {
class Program {
static void Main(string[] args) {
Student s = new Student(\张三\学生\ PersonWork(s);
Teacher t=new Teacher(\李斯\教师\ PersonWork(t); }
private static void PersonWork(Person Person) { Console.WriteLine(Person.Work()); } }
public class Person {
public string name; public Person(string name) { this.name = name; } public virtual string Work()
{ return string.Format(\早上8:30开始\ }
public class Student : Person {
private string type;
public Student(string name, string type) : base(name) { this.type = type; } public override string Work() {
return string.Format(\早上8:30开始上课\ } }
public class Teacher : Person
33