zoukankan      html  css  js  c++  java
  • 覆盖

    如何用子类的成员覆盖基类的成员。

    Fruit 类

    using UnityEngine;
    using System.Collections;
    
    public class Fruit 
    {
        public Fruit ()
        {
            Debug.Log("1st Fruit Constructor Called");
        }
    
        //这些方法是虚方法,因此可以在子类中
        //将它们覆盖
        public virtual void Chop ()
        {
            Debug.Log("The fruit has been chopped.");        
        }
    
        public virtual void SayHello ()
        {
            Debug.Log("Hello, I am a fruit.");
        }
    }

    Apple 类

    using UnityEngine;
    using System.Collections;
    
    public class Apple : Fruit 
    {
        public Apple ()
        {
            Debug.Log("1st Apple Constructor Called");
        }
    
        //这些方法是覆盖方法,因此
        //可以覆盖父类中的任何
        //虚方法。
        public override void Chop ()
        {
            base.Chop();
            Debug.Log("The apple has been chopped.");        
        }
    
        public override void SayHello ()
        {
            base.SayHello();
            Debug.Log("Hello, I am an apple.");
        }
    }

    FruitSalad 类

    using UnityEngine;
    using System.Collections;
    
    public class FruitSalad : MonoBehaviour 
    {    
        void Start () 
        {
            Apple myApple = new Apple();
    
            //请注意,Apple 版本的方法
            //将覆盖 Fruit 版本。另外请注意,
            //由于 Apple 版本使用“base”关键字
            //来调用 Fruit 版本,因此两者都被调用。
            myApple.SayHello();
            myApple.Chop();    
    
            //“覆盖”在多态情况下也很有用。
            //由于 Fruit 类的方法是“虚”的,
            //而 Apple 类的方法是“覆盖”的,因此
            //当我们将 Apple 向上转换为 Fruit 时,
            //将使用 Apple 版本的方法。
            Fruit myFruit = new Apple();
            myFruit.SayHello();
            myFruit.Chop();
        }
    }
  • 相关阅读:
    1006.Web安全攻防靶场之WebGoat – 2
    1005.Web安全攻防靶场之WebGoat – 1
    1004.Google Hack技术
    1003.漏洞及渗透练习平台
    exynos4412—UART裸板复习
    Linux3.5—IIC学习分析
    Linux3.5—视屏模块学习与分析
    Linux-3.5-Exynos4412驱动分层分离
    Linux字符设备学习,总结
    学习/linux/list.h_双链表实现
  • 原文地址:https://www.cnblogs.com/Mr-Prince/p/14142102.html
Copyright © 2011-2022 走看看