Java interface 关键字

实例

interface 接口是一个抽象的 "类",用于将相关方法与 "空" 主体分组:

  1. interface Animal {
  2. public void animalSound(); // interface method (does not have a body)
  3. public void sleep(); // interface method (does not have a body)
  4. }
  5. class Pig implements Animal {
  6. public void animalSound() {
  7. System.out.println("The pig says: wee wee");
  8. }
  9. public void sleep() {
  10. System.out.println("Zzz");
  11. }
  12. }
  13. public class Main {
  14. public static void main(String[] args) {
  15. Pig myPig = new Pig();
  16. myPig.animalSound();
  17. myPig.sleep();
  18. }
  19. }

定义与用法

interface 关键字用于声明仅包含抽象方法的特殊类型的类。

要访问接口方法,接口必须由另一个带有 implements 关键字(而不是 extends)的类 "实现"(有点像继承)。接口方法的主体由 "implement" 类提供:

关于接口的说明:

  • 与抽象类一样,接口不能用于创建对象(在上面的实例中,不可能在 MyMain 类中创建 "Animal" 对象)
  • 接口方法没有主体——主体由 "implement" 类提供
  • 在实现接口时,必须覆盖其所有方法
  • 默认情况下,接口方法是 abstract 抽象的和 public 公共的
  • 接口属性默认为 publicstaticfinal
  • 接口不能包含构造函数(因为它不能用于创建对象)

为什么以及何时使用接口?

1) 为了实现安全性——隐藏某些细节,只显示对象(接口)的重要细节。

2) Java 不支持 "多继承"(一个类只能从一个超类继承)。但是,它可以通过接口实现,因为该类可以 实现 多个接口。

注意:要实现多个接口,请用逗号分隔它们(参见下面的实例)。


多个接口

要实现多个接口,请用逗号分隔它们:

实例
  1. interface FirstInterface {
  2. public void myMethod(); // interface method
  3. }
  4. interface SecondInterface {
  5. public void myOtherMethod(); // interface method
  6. }
  7. // DemoClass "implements" FirstInterface and SecondInterface
  8. class DemoClass implements FirstInterface, SecondInterface {
  9. public void myMethod() {
  10. System.out.println("Some text..");
  11. }
  12. public void myOtherMethod() {
  13. System.out.println("Some other text...");
  14. }
  15. }
  16. public class Main {
  17. public static void main(String[] args) {
  18. DemoClass myObj = new DemoClass();
  19. myObj.myMethod();
  20. myObj.myOtherMethod();
  21. }
  22. }

关联页面

阅读有关接口的更多知识,可以访问本站的 Java Interface

分类导航