日期:2014-05-19  浏览次数:20742 次

用NEW重新定义方法

      interface   IStorable
      {
            void   Read(   );
            void   Write(   );
      }

      public   class   Document   :   IStorable
      {
        .........
        public   void   Write(   )
            {
                  Console.WriteLine(
                        "Document   Write   Method   for   IStorable "   );
            }
      }

      public   class   Note   :   Document
      {
        .........
        public   new   void   Write(   )
            {
                  Console.WriteLine(
                        "Implementing   the   Write   method   for   Note! "   );
            }
      }
      public   class   Tester
      {

            static   void   Main(   )
            {
                  //   create   a   document   reference   to   a   Note   object
                  Document   theNote   =   new   Note(   "Test   Note "   );


这里Note类中的write方法,用了new以后是不是就算是一个全新的方法,和原来的IStorable接口没有关系,只能算是Note类的方法呢?

Document   theNote   =   new   Note(   "Test   Note "   );里面,theNote是Document的一个引用变量,它指向一个Note的对象,Note对象没有具体的名字,还只是一个内存中的地址,可以把theNote看作同时是Document和Note的对象吗,就像一个手里抓着两个气球?


------解决方案--------------------
用了new后表示将父类的方法覆盖掉了,如果没有用new会有warning
theNote是多态性的使用,不能说是一手抓着两个气球,theNote只能说是指向了Note对象
------解决方案--------------------
new 是重写父类的方法
你这个地方 关系就是 父类实现了 接口,Note 又重写了这个方法
------解决方案--------------------
Document theNote = new Note( "Test Note " );
在栈创建 Document 的变量 指向 堆上创建的 Note对象空间
这个变量可以指向 多个这样的 Documnet或Note 对象空间