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();
  }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值