c#接口

接口使用 interface 关键字声明,它与类的声明类似。
接口本身并不实现任何功能,它只是和声明实现该接口的对象订立一个必须实现哪些行为的契约。

抽象类与接口有什么区别?
抽象类:
抽象类是使用 abstract 关键字修饰的类。
抽象类不能被实例化,只能被其他类继承。
抽象类可以包含抽象方法(只有方法声明,没有实际实现)和具体方法(有实际实现的方法)。
子类继承抽象类时,必须实现抽象类中的抽象方法。
抽象类可以包含属性、方法、构造方法,但构造方法不能用于实例化,主要用于被子类调用。
接口:
接口是使用 interface 关键字定义的。
接口只能包含抽象方法(在 JDK 1.8 之前,方法默认为 public abstract)和常量(public static final)。
类可以实现多个接口,解决了 Java 中单继承的问题。
接口支持多继承,一个接口可以继承多个接口。
JDK 1.8 引入了接口的默认方法(使用 default 关键字修饰)和静态方法(使用 static 关键字修饰)。

//以下实例定义了两个接口 IMyInterface 和 IParentInterface。
//如果一个接口继承其他接口,那么实现类或结构就需要实现所有接口的成员。
//以下实例 IMyInterface 继承了 IParentInterface 接口,因此接口实现类必须实现 MethodToImplement() 和 ParentInterfaceMethod() 方法:
interface IParentInterface
{
    void ParentInterfaceMethod();
}
interface IMyInterface : IParentInterface
{
    void MethodToImplement();
}
class InterfaceImplementer : IMyInterface
{
    static void Main()
    {
        InterfaceImplementer iImp = new InterfaceImplementer();
        iImp.MethodToImplement();
        iImp.ParentInterfaceMethod();
    }
    public void MethodToImplement()
    {
        Console.WriteLine("MethodToImplement() called.");
    }
    public void ParentInterfaceMethod()
    {
        Console.WriteLine("ParentInterfaceMethod() called.");
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值