C# 通过接口实现多重继承

using System;
using System.Collections.Generic;
using System.Text;
//通过接口实现多重继承
namespace interfaceDemo
{
    class Person {//定义实体类
        internal int age;
        internal string name;
        bool isMale;
        public Person(int age, string name, bool isMale) {//构造方法

            this.age = age;
            this.name = name;
            this.isMale = isMale;
        }
        public bool IsMale() {

            return this.isMale;
        }
    }

    interface Teacher//定义接口
    {
        string GetSchool();//接口里的方法都是抽象的
        string GetSubject();

    }
    interface Doctor
    {
        string GetHospital();
        double GetSalary();
    }

    class PersonA : Person, Teacher//继承person类、实现Teacher接口
    {

        public PersonA(int age, string name, bool isMale)
            : base(age, name, isMale)//派生类调用积累的构造方法
        { 
          
        
        }
        public string GetSchool()//实现接口的抽象方法
        {
            return "清华大学";
        }
        public string GetSubject()//实现接口的抽象方法
        {
            return "经济学";
        }


    }

    class PersonB : Person, Teacher, Doctor//继承person类,同时实现两个接口
    {

        public PersonB(int age, string name, bool isMale)
            : base(age, name, isMale)
        { 
        
        }
        public string GetSchool()
        {
            return "北京大学";
        }
        public string GetSubject()//实现接口的抽象方法
        {
            return "计算机";
        }
        public string GetHospital() {

            return "北京附属医院";
        }
        public double GetSalary() {

            return 2000;
        }

    }
    class TestInterface//测试类
    {
        static void Main(string[] args) {

            PersonA p1 = new PersonA(40, "张三", true);
            string gender = "";
            if (p1.IsMale())
            {
                gender = "男";
            }
            else {
                gender = "女";
            }
            Console.WriteLine("{0},{1},{2}岁,{3}教师,专业是{4}", p1.name, gender, p1.age, 
                p1.GetSchool(), p1.GetSubject());//调用接口已经实现的方法

            PersonB p2 = new PersonB(55, "赵六", false);
           
            if (p2.IsMale())
            {
                gender = "男";
            }
            else
            {
                gender = "女";
            }
            Console.WriteLine("{0},{1},{2}岁,{3}教师,专业是{4},\n同时也是{5}医生,工资为{6}", 
                p2.name, gender, p2.age, p2.GetSchool(), p2.GetSubject(),p2.GetHospital(),p2.GetSalary());
            Console.ReadLine();
        
        }
    }
}

 

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值