1. 程式人生 > >第二單元練習 第一題和第十一題

第二單元練習 第一題和第十一題

rtu font ani anim override introduce return tel else

第一題

animal類

class Animal
{
private bool m_sex;
private int m_age;
public bool Sex
{
get { return m_sex; }
set { m_sex = value; }
}
public int Age
{
get { return m_age; }
set { m_age = value; }
}
public Animal()
{
Sex = false;
}
public virtual void Introduce()
{
if (Sex == true)
Console.WriteLine("This is a male Animal!");
else
Console.WriteLine("This is a female Animal!");
}
}
class Dog : Animal
{
public Dog()
{
Sex = true;
}
public override void Introduce()
{
if (Sex == true)
Console.WriteLine("This is a male Dog!");
else
Console.WriteLine("This is a female Dog!");
}
}
class Cat : Animal
{
public override void Introduce()
{
if (Sex == true)
Console.WriteLine("This is a male Cat!");
else
Console.WriteLine("This is a female Cat!");
}
}

主函數

Animal ani = new Animal();
ani.Introduce();
Dog dog = new Dog();
dog.Introduce();
Cat cat = new Cat();
cat.Introduce();
Console.WriteLine("按回車鍵結束");
Console.ReadKey();

第十一題

animal類

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;
m_sound = "Howl";
}
public virtual string Roar()
{
return Sound;
}
}
class Dog : Animal
{
public Dog()
{
Sex = true;
Sound = "Wow...";
}
public override string Roar()
{
return "Dog:" + Sound;
}
}
class Cat : Animal
{
public Cat()
{
Sound = "Miaow...";
}
public override string Roar()
{
return "Cat:" + Sound;
}
}
class Cow : Animal
{
public Cow()
{
Sound = "Moo...";
}
public override string Roar()
{
return "Cow:" + Sound;
}
}

主函數

Animal animal;
Dog dog = new Dog();
animal = dog;
Console.WriteLine(animal.Roar());
Cat cat = new Cat();
animal = cat;
Console.WriteLine(animal.Roar());
Cow cow = new Cow();
animal = cow;
Console.WriteLine(animal.Roar());
Console.WriteLine("按回車鍵結束");
Console.ReadKey();

第二單元練習 第一題和第十一題