接口使用 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.");
}
}