认证题 2-11

   实现多态

1.Animal.cs(类文件)

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

namespace ConsoleApplication1
{
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()
{
m_sex = false;
Sound = "Howl...";
}
public virtual string Rore()
{
return Sound;
}
}
class Dog : Animal
{
public Dog()
{
Sex = true;
Sound = "Wow...";
}
public override string Rore()
{

return "Dog:" + Sound;
}
}
class Cat : Animal
{
public Cat()
{
Sound = "Miaow...";
}
public override string Rore()
{

return "Cat:" + Sound;
}
}
class Cow : Animal
{
public Cow()
{
Sound = "Moo...";
}
public override string Rore()
{

return "Cow:" + Sound;
}
}

}

2.实例化

static void Main(string[] args)
{
string s1,s2,s3;
Animal animal = new Cow();
s1=animal.Rore();
Console.WriteLine(s1);
Animal dog = new Dog();
s2=dog.Rore();
Console.WriteLine(s2);
Animal cat = new Cat();
s3=cat.Rore();
Console.WriteLine(s3);
}

3.结果

posted @ 2017-09-17 11:03  ~波妞~  阅读(105)  评论(0编辑  收藏  举报