一、接口的继承语法
在 Java 中,接口继承使用关键字 “extends”,与类继承相似。下面是接口继承的语法示例:
interface Animal {
void eat();
void sleep();
}
interface Bird extends Animal {
void fly();
}
二、继承的特点:
- 继承可以帮助我们在新的接口中包含旧接口的方法签名。
- 接口之间可以进行多层继承,允许创建接口的层次结构。
三、实例解析
让我们通过一些实例来进一步理解接口之间的继承。
1、接口继承单一接口的例子:
interface Mammal {
void eat();
void sleep();
}
interface Human extends Mammal {
void talk();
}
class Person implements Human {
public void eat() {
System.out.println("Person is eating.");
}
public void sleep() {
System.out.println("Person is sleeping.");
}
public void talk() {
System.out.println("Person is talking.");
}
}
在上面的示例中,接口 “Mammal” 定义了 “eat” 和 “sleep” 方法,在接口 “Human” 中继承了 “Mammal”,并添加了额外的 “talk” 方法。通过实现接口 “Human” 的类 “Person”,我们需要实现全部三个方法。
2、接口继承多个接口的例子:
interface Flyable {
void fly();
}
interface Swimmable {
void swim();
}
interface Bird extends Flyable, Swimmable {
void chirp();
}
class Duck implements Bird {
public void fly() {
System.out.println("Duck is flying.");
}
public void swim() {
System.out.println("Duck is swimming.");
}
public void chirp() {
System.out.println("Duck is chirping.");
}
}
在上述例子中,接口 “Bird” 在继承接口 “Flyable” 和 “Swimmable” 的同时定义了一种 “chirp” 方法。类 “Duck” 实现了接口 “Bird”,需要实现全部三个方法。