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 修饰符修饰它。

  • 相关阅读:
    常用的学生、课程、成绩、教师表的查询
    flutter 自定义TabBar
    Flutter 设置input边框
    Flutter ReorderableListView 可拖拽的列表
    Flutter NotificationListener 监听列表的滚动
    Flutter 使用Tabbar不要Title
    Nestjs 验证对象数组
    postman 发送数组
    JS面向切面编程AOP
    什么是匿名函数、什么是闭包函数?
  • 原文地址:https://www.cnblogs.com/wwwfj/p/3349285.html
Copyright © 2011-2022 走看看