shangxijie

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

/**

the "new"

**/

using System;
namespace animals
{

  class dog{
public dog(){
}
    public virtual void gnar(){

      Console.WriteLine("Won.Won...");

    }

  }

  class bigdog:dog{
public bigdog(){
}
    public new void gnar(){

      Console.WriteLine("Woooooonn...");

    }

  }

  class Program{
        static void Main(string[] args){

      dog tom = new dog();

      Console.WriteLine("a little dog..");

      tom.gnar();

      tom = new bigdog();

      Console.WriteLine("a big dog..");

      tom.gnar();

    }

  }

}

/**

the "override"

**/

using System;
namespace animals
{

  class dog{
public dog(){
}
    public virtual void gnar(){

      Console.WriteLine("Won.Won...");

    }

  }

  class bigdog:dog{
public bigdog(){
}
    public override void gnar(){

      Console.WriteLine("Woooooonn...");

    }

  }

 

  class Program{
        static void Main(string[] args){

      dog tom = new dog();

      Console.WriteLine("a little dog..");

      tom.gnar();

      tom = new bigdog();

      Console.WriteLine("a big dog..");

      tom.gnar();

    }

  }

}

 

override是为多态服务的,这点在模板方法模式中体现的尤为明显,在对象的定义中 父类 x= new 子类(),x.method(),如果这个方法是子类override父类的,那么调用的是子类的方法

但是如果这个方法是子类new的,那么调用的是父类的

 

posted on 2008-07-24 10:37  尚希杰  阅读(271)  评论(0编辑  收藏  举报