C#继承小练习

实验要求

根据类图编写程序,其中Person中的Eat方法定义为虚方法,Baby和Adult类对该方法进行重写。

(华北理工大学信管专业C#课程作业--大一下学期)

解:

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

namespace tets
{
    class Program
    {
        static void Main(string[] args)
        {
            Person baby = new Baby("zh","女");
            baby.Eat();
            Adult adult = new Adult("yy","男","大学");
            adult.Eat();
            adult.Speak();
            Console.ReadKey();

        }
    }
    /// <summary>
    /// 父类
    /// </summary>
    class Person
    {
 
        private string name;
        private string gender;
        public Person()
        {

        }
        public Person(string name,string gender)
        {
            this.gender = gender;
            this.name = name;
            Console.WriteLine("我是人,性别{0},我叫{1}", gender, name);
        }
        public virtual void Eat()
        {
            Console.WriteLine("我是人,我爱吃水果");
        }
    }
    /// <summary>
    /// 子类Baby
    /// </summary>
    class Baby : Person
    {
        public Baby(string name,string gender):base(name,gender)
        {

        }
 
        public override void Eat()
        {
            Console.WriteLine("我是宝宝,我爱喝牛奶");

        }


    }
    /// <summary>
    /// 子类Adult
    /// </summary>
    class Adult : Person
    {
        private string degree;
        public Adult(string name,string gender,string degree)
        {
            this.degree = degree; 
            Console.WriteLine("我是{0},性别{1},我的学历是{2}", name,gender,degree);
        }
        public override void Eat()
        {
            Console.WriteLine("我是成年人,我爱吃面包");
        }
        public void Speak()
        {
            Console.WriteLine("我是成年人,我会唱跳rap和篮球");
        }
    }
}

 

转载于:https://www.cnblogs.com/yorkmass/p/11109810.html

评论将由博主筛选后显示,对所有人可见 | 还能输入1000个字符 “速评一下”
©️2020 CSDN 皮肤主题: 编程工作室 设计师:CSDN官方博客 返回首页