Java 接口

Java接口/interface

Java中,实现抽象的另一种方法是接口。

接口/interface是一个完全的“抽象类”,包含了一组没有实体的方法声明。

示例

// interface
interface Animal {
  public void animalSound(); // interface 方法 (没有实体)
  public void run(); // interface 方法 (没有实体)
}

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

// Interface
interface Animal {
  public void animalSound(); // interface 方法 (没有实体)
  public void sleep(); // interface 方法 (没有实体)
}

// Pig "implements" Animal 接口
class Pig implements Animal {
  public void animalSound() {
    // 这里提供了animalSound()方法的实体
    System.out.println("小猪说: 呜呜");
  }
  public void sleep() {
    // sleep()方法的实体
    System.out.println("Zzz");
  }
}

class MyMainClass {
  public static void main(String[] args) {
    Pig myPig = new Pig();  // 创建Pig对象
    myPig.animalSound();
    myPig.sleep();
  }
}

接口说明:

  • 与抽象类一样,接口不能用于创建对象(在上面的示例中,不能在MyMainClass中创建“Animal”对象)
  • 接口方法没有主体 - 主体由“实现”类提供
  • 在实现接口时,必须重写它的所有方法
  • 接口方法默认是abstractpublic
  • 接口属性默认为publicstaticfinal
  • 接口不能包含构造函数(因为它不能用于创建对象)

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

  1. 安全性 - 对外隐藏对象细节,只暴露必须暴露的内容(接口函数)。

  2. Java不支持“多重继承”(一个类只能继承一个父类)。但是,一个类可以实现多个接口。注意: 实现多个接口时,接口之间用逗号分隔(参见下面的示例)。

多个接口

示例

interface FirstInterface {
  public void myMethod(); // interface 方法
}

interface SecondInterface {
  public void myOtherMethod(); // interface 方法
}

// DemoClass实现(implements)了FirstInterface和SecondInterface接口
class DemoClass implements FirstInterface, SecondInterface {
  public void myMethod() {
    System.out.println("Some text..");
  }
  public void myOtherMethod() {
    System.out.println("Some other text...");
  }
}

class MyMainClass {
  public static void main(String[] args) {
    DemoClass myObj = new DemoClass();
    myObj.myMethod();
    myObj.myOtherMethod();
  }
}
posted @ 2019-10-23 11:32  吴吃辣  阅读(192)  评论(0编辑  收藏  举报