日期:2014-05-18 浏览次数:21014 次
先建立一个狗的类(类:其实就是具有共同特征的事物的抽象) class Dog { private string name; public Dog(string name) { this.name = name; } public void 叫() { Console.WriteLine("旺旺"); } } 然后建一个猫的类 class Cat { private string name; public Cat(string name) { this.name = name; } public void () { Console.WriteLine("喵喵"); } } 比如后面再添加牛,马等等这些动物,我们发现这些有很多相似的地方,那么我们就把他们这些一样的行为都抽象起来,那么现在就是抽象类,和继承出场的时候了
abstract class Animal //抽象类(动物) { private string name; public Animal(string name) { this.name = name; } public abstract void jiao(); //因为呢,动物都会叫所以写一个叫的抽象方法,这个呢,需要在派生类中实现 } class Dog : Animal //继承Animal { public Dog(string name):base(name) 调用Animal构造函数 { } public override void jiao() //重写派生类的叫的方法,实现自己的叫 { Console.WriteLine("旺旺"); } } class Cat : Animal //继承Animal { public Cat(string name):base(name) { } public override void jiao() { Console.WriteLine("喵喵"); } }
abstract class Animal { private string name; public Animal(string name) { this.name = name; } public abstract void jiao(); } interface IFly { void Fly(); } class Dog : Animal { public Dog(string name):base(name) { } public override void jiao() { Console.WriteLine("旺旺"); } } class Cat : Animal { public Cat(string name):base(name) { } public override void jiao() { Console.WriteLine("喵喵"); } } class Laoying : Animal,IFly { public Laoying(string name) : base(name) { } public override void jiao() { Console.WriteLine("老鹰叫"); } public void Fly() //实现接口 { Console.WriteLine("老鹰在天空中高高的飞翔"); } }
class Fuqin { public virtual void Chang() { Console.WriteLine("我是父亲,我用我的方式去唱"); } } class Erzi : Fuqin { public override void Chang() { Console.WriteLine("我是儿子,我用我的方式去唱"); } }