编写一个C#应用程序,定义学生类Student及其派生类Undergraduate和Graduate,实现方法的重载和多态。

如题所述

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CShap_Test1
{
class Student
{
public string Name { get; set; }
public int Num { get; set; }

public Student()
:this("",0)
{

}

public Student(string name, int num)
{
Name = name;
Num = num;
}
virtual public void speak()
//声明为虚函数,下面的派生类就可以重载了
{
Console.WriteLine("I am a student!");
}

public override string ToString()
//对Object基类方法ToString的重载
{
return string.Format("Name : {0} Num : {1}", Name, Num);
}
}

class Undergraduate : Student
{
public double Score { get; set; }

public Undergraduate(string name, int num, double score)
: base(name, num)
{
Score = score;
}

new public void speak()
//注意这里,new是隐藏 而不是重载 注意在main函数里面多态处理时候的输出
{
Console.WriteLine("I am an undergraduated student!");
}

public override string ToString()
{
return base.ToString() + string.Format(" Score : {0}", Score);
}
}

class Graduate : Student
{
public bool Employeed { get; set; }

public Graduate(string name, int num, bool employeed)
: base(name, num)
{
Employeed = employeed;
}

public override void speak()
//重载基类的speak方法
{
Console.WriteLine("I am a graduated student!");
}

public override string ToString()
{
return base.ToString() + string.Format(" Employeed : {0}", Employeed);
}
}
class Program
{
static void Main(string[] args)
{
Student s = new Student("Jack", 20101);
Console.WriteLine(s);
s.speak();

Console.WriteLine();
Undergraduate u = new Undergraduate("Marry", 20133, 89.2);
Console.WriteLine(u);
u.speak();

Console.WriteLine();
Graduate g = new Graduate("Tick", 20198, true);
Console.WriteLine(g);
g.speak();

Console.WriteLine("\nPolymophsim:");
//多台处理
Student[] p = new Student[3];
//student指针可以指向派生类
p[0] = s;
p[1] = u;
p[2] = g;
foreach (var t in p)
{
t.speak();
Console.WriteLine(t);
}
}
}
}
温馨提示:内容为网友见解,仅供参考
无其他回答

编写一个C#应用程序,定义学生类Student及其派生类Undergraduate和Gradua...
virtual public void speak()\/\/声明为虚函数,下面的派生类就可以重载了 { Console.WriteLine("I am a student!");} public override string ToString()\/\/对Object基类方法ToString的重载 { return string.Format("Name : {0} Num : {1}", Name, Num);} } class Undergraduate : Student {...

相似回答