Java编程语言中,接口是一种定义了一组方法(仅有方法声明,无任何方法实现的定义)的集合,这些方法的访问修饰符都是public,可以被其他程序调用。实现接口中的所有方法,这样的类被称为实现类。和许多面向对象编程语言一样,Java 是为了实现代码重用而引入接口这一概念。
一、接口的定义与继承
接口定义了一组方法的规范,没有提供任何方法的实现,这些方法会作为规范被其他类实现,实现这些方法的类就可以向外界提供这些方法的实现。 接口定义的方法默认使用public abstract修饰符,public abstract可以省略。
例子:
interface Animal{ void eat(); void sleep(); } public class Dog implements Animal{ public void eat(){ System.out.println("Dog eats meat."); } public void sleep(){ System.out.println("Dog sleeps soundly."); } }
找到实现类Dog,它必须实现Animal接口的所有方法,否则编译器将发现一个编译时错误。在方法中,我们实现了eat和sleep方法,Dog类现在可以作为Animal类型使用,例如:
class Test{ public static void main(String[] args){ Animal a = new Dog(); a.eat(); a.sleep(); } }
在Java编程中,接口可以被其他接口继承。
例子:
interface Animal{ void eat(); void sleep(); } interface Lion extends Animal{ void roar(); }
Lion继承Animal接口,可以继承其方法,不需要再重复其框架
二、接口的多重继承
Java允许一个接口继承多个接口,称为多重继承,并且允许继承链中的同名方法,例如:
interface Animal{ void eat(); void sleep(); } interface Mammal{ void giveBirth(); } interface Dog extends Animal, Mammal{ void bark(); }
这个例子展示了Dog接口多重继承Animal和Mammal接口,这两个接口中都有未实现的方法eat() 和sleep(),这样的接口可以使实现类更加具有灵活性。
三、接口的默认方法和静态方法
Java 8引进了默认方法和静态方法的概念,默认方法允许在不破坏已有实现情况下向接口添加新方法。接口中的静态方法可以在接口中直接调用,而无需实现类。它们都使用default关键字来定义。
例子:
interface Vehicle{ void run(); default void stop(){ System.out.println("Stop vehicle."); } static void horn(){ System.out.println("Make noise!"); } } class Bike implements Vehicle{ public void run(){ System.out.println("Bike is running!"); } } class Test{ public static void main(String[] args){ Vehicle v1 = new Bike(); v1.run(); v1.stop(); Vehicle.horn(); } }
在运行main方法后,我们可以看到Bike类实现了接口中的run方法,同时默认方法stop方法的实现也被调用,Vehicle中的静态方法horn()直接被调用。