c# 基类、派生类应用

来源:互联网 发布:如何设计软件 编辑:程序博客网 时间:2024/06/07 05:15

      最近在学接口,在网上总是会搜到“基类”的字眼,想想应该有类似的地方,所以就一起学习了一下。先说基类、派生类,个人理解就是类之间的继承 。直接上代码:

  class entertainment    {       public void type()        {            Console.WriteLine("entertainment: This is a kind of entertainment");        }    }   class Shopping : entertainment    {       public void type()        {            Console.WriteLine("shopping (type) : Go shopping with my friends");        }       public void type1()       {           Console.WriteLine("shopping (type1) : Go shopping ");       }    }   class Hiking : entertainment    {            public void type()        {            Console.WriteLine("Hiking : Go hiking  on Sunday");        }    }

为了做区分,所以在实例化的时候,做了不同的对比:

   static void Main(string[] args)        {         entertainment em=new entertainment();         Shopping sp = new Shopping();            Hiking hk=new Hiking();            entertainment ems = new entertainment();            ems=(entertainment)sp;           em.type();            sp.type();            sp.type1();            hk.type();            ems.type();        }

跑出来的结果如下:


由最终结果可以看出:

1.派生类继承基类之后,就自动添加了基类的方法,对于会调用相同方法的类来说,这一点很方便。

2当派生类shopping继承基类entertainment之后,如果内部方法的名称与基类相同,默认输出的是派生类的结果,只有在强制转换之后才会输出基类的方法运行的结果,针对于这一情况,有一点不太明白,网上有很多讲到方法相同的时候隐藏基类方法,但是既然都已经默认是派生类的方法了,何必要再隐藏基类的呢?


以上是个人初学尝试之后的一些拙见与疑问,也请高手们帮忙解惑,方便大家共同进步 。

0 0