zoukankan      html  css  js  c++  java
  • 虚方法

    虚方法虽然自己一直自以为了解,但是以前还总是不太确定,今天确定一下:

    namespace test1
    {
        class Program
        {
            public static void Main(string[] args)
            {
                father f = new sun();//注意此处,用子类实例化一个父类对象,执行方法的时候执行的是父类中的方法
                f.jump();
                Console.ReadKey();
            }
        }
        class father
        {
            int a = 4;
            public void jump()
            {
                Console.WriteLine("father jump");
            }
        }
        class sun:father
        {
            int b = 6;
            public void jump()
            {
                Console.WriteLine("sum jump");
            }
        }
    }

    上面的显示结果是father jump,因为父类中的jump不是虚方法,所以不能被重载,即父类的jump就是父类原来的jump。

    下面,将父类的jump定义为虚方法,它将被子类重写,再用子类实例化一个父类对象的时候,执行父类的中方法将是被子类重写过的方法了。

    namespace test1
    {
        class Program
        {
            public static void Main(string[] args)
            {
                father f = new sun();
                f.jump();
                Console.ReadKey();
            }
        }
        class father
        {
            int a = 4;
            public virtual void jump()
            {
                Console.WriteLine("father jump");
            }
        }
        class sun:father
        {
            int b = 6;
            public override void jump()
            {
                Console.WriteLine("sum jump");
            }
        }
    }



  • 相关阅读:
    设计模式-14-桥接模式
    设计模式-13-中介者模式
    设计模式-12-命令模式
    设计模式-11-外观模式
    设计模式-10-装饰器
    设计模式-9-模板
    设计模式-8-适配器模式-组合
    设计模式-8-适配器模式-继承
    设计模式-7-策略模式+工厂模式
    设计模式-7-策略模式
  • 原文地址:https://www.cnblogs.com/ensleep/p/2556078.html
Copyright © 2011-2022 走看看