为了达到代码复用的效果,将不变的部分放在父类,变化的部分放在子类,如下代码实例,以备回忆
Code
using System;
public class MyClass
{
public static void Main()
{
AnimalTemplet animal;
animal=new Cat();
animal.Eat();
animal.Walk();
animal.Display();
animal=new Tiger();
animal.Eat();
animal.Walk();
animal.Display();
Console.ReadLine();
}
}
public abstract class AnimalTemplet
{
abstract public void Display();
public void Eat()
{
Console.WriteLine("用嘴吃东西");
}
public void Walk()
{
Console.WriteLine("用腿跑路");
}
}
public class Cat:AnimalTemplet
{
public Cat()
{
Console.WriteLine("我是猫");
}
public override void Display()
{
Console.WriteLine("个头小");
}
}
public class Tiger:AnimalTemplet
{
public Tiger()
{
Console.WriteLine("我是老虎");
}
public override void Display()
{
Console.WriteLine("个头大");
}
}
猫和老虎走路都用腿,吃饭都用嘴(废话),但是一个大,一个小。。。。。运行结果: