首页 > 代码库 > C#类的继承

C#类的继承

    public class Animal    {        public string word="";        //virtual表示虚方法,用以被重写        public virtual void say(){ word = "I am an animal.";}    }    //override表示重写(覆盖)    public class Cat : Animal    {        public override void say(){ word = "I am a cat.";}    }    public class Dog : Animal    {        public new void say(){ word = "I am a dog.";}    }

上面的三个类(Cat,Dog,Cow)继承类Animal。下面进行几种实例化测试:

1.

Animal animal = new Cat();animal.say();alert(animal.word);

输出的是 “I am a cat.”

2.

Cat animal = new Cat();animal.say();alert(animal.word);

输出的也是 “I am a cat.” 

3.

Animal animal = new Dog();animal.say();alert(animal.word);

输出的是“I am an animal” ,

4.

Dog animal = new Dog();animal.say();alert(animal.word);

输出的是“I am an dog”

ps:上面可以看出override和new形式的区别

C#类的继承