zoukankan      html  css  js  c++  java
  • c#中的new和override的实例

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    /*
     简单说,抽象方法是需要子类去实现的。虚方法是已经实现了的,可以被子类覆盖,也可以不覆盖,取决于需求。
    
    抽象方法和虚方法都可以供派生类重写。
     */
    namespace MySpace
    {
        class dad
        {
            protected string name;      //成员变量
    
            public dad(string n)        //构造函数
            {
                name = n;
            }
            public void say()           //基类say方法
            {
                Console.WriteLine("I am {0}.", name);
            }
            public virtual void growup()    //基类growup方法 虚函数
            {
                Console.WriteLine("{0} has grown old.", name);
            }
        }
        class son : dad         //继承父亲
        {
            public son(string n)    //构造函数
                : base(n)
            {
                //name = n;
            }
            public new void say()   //在派生类中定义的和基类中的某个方法同名的方法,使用 new 关键字定义
            {
                Console.WriteLine("I am {0} and a son.", name);
            }
            public override void growup()   //重写(override)是用于重写基类的虚方法,这样在派生类中提供一个新的方法,继承类中的重写虚函数需要声明关键字 override
            {
                //base.growup();
                Console.WriteLine("{0} is growing up.", name);
            }
        }
        class entrance
        {
            public static void Main()
            {
                dad grandpa = new dad("grandpa");       //用父类生成的父类对象
                grandpa.say();      //父类say方法的调用
                grandpa.growup();   //父类growup方法的调用
    
                Console.WriteLine("
    new son("father")");
                dad father = new son("father"); //用子类生成的父类对象
                father.say();           //调用父类方法,访问隐藏方法是父类的方法
                father.growup();        //调用子类方法,访问重写方法是子类的方法
    
                Console.WriteLine("
    son tom = new son("Tom")");
                son tom = new son("Tom");   //用子类生成的子类对象
                tom.say();  //访问隐藏方法是子类的方法,访问重写方法是子类的方法
                tom.growup();
    
                //Console.ReadKey();
            }
        }
    }
    
    /*
    
    I am grandpa.
    grandpa has grown old.
    
    new son("father")
    I am father.
    father is growing up.
    
    son tom = new son("Tom")
    I am Tom and a son.
    Tom is growing up.
     * 
     * 上边的结果:
    
     1)用父类生成的父类对象,grandpa,访问隐藏方法是父类的方法,访问重写方法是父类的方法
     2)用子类生成的父类对象,father,访问隐藏方法是父类的方法,访问重写方法是子类的方法
     3)用子类生成的子类对象,son,访问隐藏方法是子类的方法,访问重写方法是子类的方法
    请按任意键继续. . .
    */
    

      这个实例比较好,因此特此转载。说明了new和override的区别。

  • 相关阅读:
    JavaWeb核心编程之(四.1)JSP
    一起来说 Vim 语
    你应该知道的基础 Git 命令
    Git 系列(五):三个 Git 图形化工具
    Git 系列(四):在 Git 中进行版本回退
    Git 系列(三):建立你的第一个 Git 仓库
    Git 系列(二):初步了解 Git
    Git 系列(一):什么是 Git
    JavaWeb核心编程之(三.6)HttpServlet
    多线程:子线程执行完成后通知主线程
  • 原文地址:https://www.cnblogs.com/CodeWorkerLiMing/p/11886106.html
Copyright © 2011-2022 走看看