关于继承的浅显的知识

 

继承就是为了提高代码的复用性,实现多态看下这段简单的代码

一.继承中最简单的应用

     public class FatherTest

    {

        public void OutPutMyName()

        {

            Console.WriteLine("I am a Father!");

        }

        public FatherTest()

        {}

    }

    public class SonTest : FatherTest

    {

        public SonTest()

        { }

    }

class Program

    {

        static void Main(string[] args)

        {

           FatherTest newM=new FatherTest();

            newM.OutPutMyName();

            SonTest newS = new SonTest();

            newS.OutPutMyName();

}

}

输出结果:

这是最简单的继承了,子类继承了父类的方法。

二.隐藏了父类的方法

    public class FatherTest

    {

        public void OutPutMyName()

        {

            Console.WriteLine("I am a Father!");

        }

        public FatherTest()

        {}

    }

    public class SonTest : FatherTest

    {

        public SonTest()

        { }

        public void OutPutMyName()

        {

            Console.WriteLine("I am a son!");

        }

    }class Program

    {

         static void Main(string[] args)

        {

           FatherTest newM=new FatherTest();

            newM.OutPutMyName();//调用父类本身的方法

            SonTest newS = new SonTest();

            newS.OutPutMyName();//调用子类本身的方法

            MotherTest newT = new SonTest();

              newT.OutPutMyName();

}

输出结果:

在第一个例子中子类继承了父类的方法,在此子类中自己有了一个与父类同名的方法OurPutMyName,编译器会提醒用new关键字来声明,意思是这个方法已经隐藏了继承了的父类的同名方法,这样不加new 也可以通过编译并运行,因为编译器理解是要隐藏父类的同名方法。在方法前面New关键字的意义呢就是在子类中重写一个与父类同名的方法,这个方法与父类无关。

在这个例子中newT这个实例声明的时候是父类的对象,这在编译的时候已经定了,不管“=”右边是父类还是子类的,newT在编译的时候已经存储了对Father的引用,它看不到子类里面的新方法,所以此对象还是会调用Father类的方法。这就相当于C++里面的静态联编,即编译时已经生成。

三. 多态

   这个例子中我们引入多态的概念了

public class FatherTest

    {

        public virtual void OutPutMyName()

        {

            Console.WriteLine("I am a Father!");

        }

        public FatherTest()

        {}

    }

    public class SonTest : FatherTest

    {

        public SonTest()

        { }

        public override void OutPutMyName()

        {

            Console.WriteLine("I am son!");

        }

}

class Program

    {

        static void Main(string[] args)

        {

           FatherTest newM=new FatherTest();

            newM.OutPutMyName();

            SonTest newS = new SonTest();

            newS.OutPutMyName();

            FatherTest newT = new SonTest();

            newT.OutPutMyName();

}

}

输出结果:

这个例子只是将父类的方法变成virtual的了结果就不一样了,父类标志为Virtual的,是为了让子类选择是继承这个方法,还是重写,如果子类有个同名方法并且加以override修饰,这说明子类覆盖(重写)了父类的同名方法,那么就要调用子类的这个方法,如果子类没有override父类的方法,那么子类就继承了父类的这个方法。结果是这样,那么原理呢?是这样的: newT这个对象创建的时候,编译器就已经检测到它本身的方法是最初的实现是子类的OutPutMyName(因为override了),父类的OutPutMyName方法标志为Virtual的,使得在编译时生成代码,在运行时检测,查找它的最初实现(如果子类override了,那么它就是这个对象的初次实现,如果不加override,编译器会当作加了new 关键字来处理,即重新写了一个方法,这个跟父类没有任何的关系),即使把它声明为基类型,还是执行检测到的代码。这就是多态性,即C++中 的动态联编。
posted @ 2007-12-20 12:09  慧致澜馨  阅读(303)  评论(0编辑  收藏  举报