本帖最后由 郑丹丹1990 于 2013-5-17 08:24 编辑
- namespace 继承
- {
- class Program
- {
- static void Main(string[] args)
- {
- son s = new son("xioaming", 23, 175);
- Console.WriteLine(s.Height);
- s.SayHello();
- s.speak();
- Father f = (Father)new son("tom", 40, 180);
- f.speak();
- Console.ReadKey();
- }
- }
- public class Father
- {
- public string Name { get; set; }
- public int Age { get; set; }
- public double Height { get; set; }
- public Father(string name,int age, double height)
- {
- this.Name=name;
- this.Age=age;
- this.Height=height;
- }
- public void SayHello()
- {
- Console.WriteLine("father.sayhello()");
- }
- public virtual void speak()
- {
- Console.WriteLine("father.virtual.speak()");
- }
- }
- public class son:Father
- {
- public son(string name, int age, double height)
- : base(name, age, height)
- {
- this.Name = name;
- this.Age = age;
- this.Height = height;
- }
- public override void speak()
- {
- Console.WriteLine("son.speak()");
- }
- }
- }
复制代码 f.speak()是调用子类的方法??这是为什么呀?不是已经把Son强制转化为Father了吗?为何不调用基类中的方法?
另:若把son中的speak()方法的override换成new,则会调用父类方法。这又是为何?? |