zoukankan      html  css  js  c++  java
  • new 与override 区别

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;

    namespace Newoverride
    {
        class Dad
        {
            public Dad()
            {
                Console.WriteLine("Dad construtor");
            }
            public virtual void method()
            {
                Console.WriteLine("Dad method");
            }
        }
        class SmallSon : Dad
        {
            public SmallSon()
            {
                Console.WriteLine("Smallson construtor");
            }
            public override void method()
            {
                Console.WriteLine("override Smallson method");
            }
        }
        class BigSon : Dad
        {
            public BigSon()
            {
                Console.WriteLine("BigSon construtor");
            }
            public new void method()
            {
                Console.WriteLine("new BigSon method ");
            }
        }
        class Program
        {
            static void Main(string[] args)
            {
                Dad f = new Dad();
                f.method();
                Dad f1 = (Dad)new SmallSon();// 先初始化Dad(),然后再初始化SmallSon()
                f1.method();//override smallson method
                Dad f2 = (Dad)new BigSon();// 先初始化Dad(),然后再初始化Bigson()
                f2.method();// Dad method
                BigSon s = new BigSon();
                s.method();
               
            }
        }
    }

    2.从输出结果可知:
       第47行,先初始化基类再初始化子类构建器;
       第48行,利用override重写了基类方法,得到的是子类方法;
       第50行,利用new没有重写基类方法,得到的是基类方法;
       第51、52行,输出子类方法结果。
       所以,使用new没有用到基类方法,而是重新定义了子类方法,只不过方法名称与基类相同。
    使用 new 修饰符显式隐藏从基类继承的成员。若要隐藏继承的成员,请使用相同名称在派生类中声明该成员,并用 new 修饰符修饰它。

  • 相关阅读:
    《敏捷软件需求》阅读笔记三
    《敏捷软件需求》阅读笔记二
    《敏捷软件需求》阅读笔记一
    《需求工程-软件建模与分析》阅读笔记三
    《需求工程-软件建模与分析》阅读笔记二
    《需求工程-软件建模与分析》阅读笔记一
    C#.NET程序设计实验三实验报告
    C#.NET程序设计实验二实验报告
    C#.NET程序设计实验一实验报告
    oracle——存储数据时的编码问题
  • 原文地址:https://www.cnblogs.com/wwwfj/p/3349285.html
Copyright © 2011-2022 走看看