C#中的继承和多态

只允许单继承,多继承可以由接口来实现,继承是可以传递的,类可以定义虚方法、虚属性、虚索引指示器,而派生类能重写这些成员,以事项面向对象编程中的多态

1.类的继承

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

class student
{
    private string xh;
    private string name;
    public student(string m_xh, string m_name)
    {
        xh = m_xh;
        name = m_name;
    }
    public virtual void display()
    {
        Console.WriteLine("学号:{0}", xh);
        Console.WriteLine("姓名:{0}", name);
    }
}

class good_student : student    //继承student类
{
    private decimal bursary = 0.0m;
    public good_student(string m_xh, string m_name, decimal m_bursary)   
        : base(m_xh, m_name)
    {
        bursary = m_bursary;
    }
    public override void display()
    {
        base.display();
        Console.WriteLine("奖学金:{0}", bursary);
    }
}

public class basetest
{
    public static void Main()
    {
        good_student gs = new good_student("1001","赵六",1200.0m);
        gs.display();
        Console.Read();
    }
}

2.接口的继承(接口里的方法必须在派生类中实现)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
interface IA     //声明接口
{
    float length();    //声明抽象成员(成员中不包含可执行代码)
    float width();
}
interface IB     //声明接口
{
    float length();   //声明抽象成员(成员中不包含可执行代码)
    float width();
}
class box : IA, IB
{
    float Iinches;
    float Winches;
    public box(float length, float width)   //构造函数
    {
        Iinches = length;
        Winches = width;
    }
    float IA.length()    //实现接口的抽象方法
    {
        return Iinches;
    }
    float IA.width()
    {
        return Winches;
    }
    float IB.length()
    {
        return Iinches * 0.178f;
    }
    float IB.width()
    {
        return Winches * 1.78f;
    }
}

public class maintest
{
    public static void Main()
    {
        box b = new box(123.0f, 456.123f);
        IA ia = (IA)b;       //显式转换创建实例对象
        IB ib = (IB)b;
        Console.WriteLine("inches:");
        Console.WriteLine("\t\t length:{0}", ia.length());
        Console.WriteLine("\t\t width:{0}", ia.width());
        Console.WriteLine("metrics");
        Console.WriteLine("\t\t length:{0}", ib.length());
        Console.WriteLine("\t\t width:{0}", ib.width());
        Console.Read();
    }
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值