这次的多态很简单,没什么知识点 。
直接贴代码了:
public abstract class Animal //建立一个抽象类
{
private bool m_sex;
private string m_sound;
public bool Sex
{
get { return m_sex; }
set { m_sex = value;}
}
public string Sound
{
get { return m_sound; }
set { m_sound = value; }
}
public Animal()
{
Sex = false;
Sound = "Howl...";
}
public abstract string Roar();
}
public class Dog:Animal
{
bool Sex=true;
string Sound = "Wow..";
public override string Roar()
{
return ("Dog:" + Sound);
}
}
public class Cat : Animal
{
bool Sex = true;
string Sound = "Miaow..";
public override string Roar()
{
return ("Cat:" + Sound);
}
}
public class Cow : Animal
{
bool Sex = true;
string Sound = "Moooo..";
public override string Roar()
{
return ("Cow:" + Sound);
}
}
主函数的代码:
Animal animal;
Dog dog = new Dog();
Cat cat = new Cat();
Cow cow = new Cow();
animal = dog;
animal = cat;
animal = cow;
Console.WriteLine(dog.Roar());
Console.WriteLine(cat.Roar());
Console.WriteLine(cow.Roar());
Console.ReadKey();
再来个图片: