专注Java教育14年 全国咨询/投诉热线:444-1124-454
赢咖4LOGO图
始于2009,口口相传的Java黄埔军校
首页 学习攻略 Java学习 Java定义接口的关键字

Java定义接口的关键字

更新时间:2022-09-20 10:48:32 来源:赢咖4 浏览1797次

Java怎样定义接口的关键字?赢咖4小编来为大家举例说明。

例子

Aninterface是一个抽象“类”,用于将相关方法与“空”主体分组:

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

// interface
interface Animal {
  public void animalSound(); // interface method (does not have a body)
  public void sleep(); // interface method (does not have a body)
}
// Pig "implements" the Animal interface
class Pig implements Animal {
  public void animalSound() {
    // The body of animalSound() is provided here
    System.out.println("The pig says: wee wee");
  }
  public void sleep() {
    // The body of sleep() is provided here
    System.out.println("Zzz");
  }
}
class MyMainClass {
  public static void main(String[] args) {
    Pig myPig = new Pig();  // Create a Pig object
    myPig.animalSound();
    myPig.sleep();
  }
}

定义和使用

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

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

多个接口

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

interface FirstInterface {
  public void myMethod(); // interface method
}
interface SecondInterface {
  public void myOtherMethod(); // interface method
}
// DemoClass "implements" FirstInterface and 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();
  }
}

以上就是关于“Java定义接口的关键字”的介绍,大家如果想了解更多相关知识,不妨来关注一下赢咖4的Java赢咖4在线学习,里面的课程内容细致全面,适合没有基础的小伙伴学习,相信对大家一定会有所帮助的哦。

提交申请后,顾问老师会电话与您沟通安排学习

免费课程推荐 >>
技术文档推荐 >>