Java 接口
接口
在 Java 中实现抽象的另一种方法是使用接口。
接口
是一个完全“抽象类”,用于将相关方法分组,这些方法具有空的方法体。
示例
// interface
interface Animal {
public void animalSound(); // interface method (does not have a body)
public void run(); // interface method (does not have a body)
}
要访问接口方法,该接口必须由另一个类使用 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 Main {
public static void main(String[] args) {
Pig myPig = new Pig(); // Create a Pig object
myPig.animalSound();
myPig.sleep();
}
}
关于接口的说明
- 与抽象类一样,接口不能用于创建对象(在上面的示例中,无法在 MyMainClass 中创建“Animal”对象)。
- 接口方法没有方法体——方法体由“实现”类提供。
- 在实现一个接口时,你必须覆盖它的所有方法
- 接口方法默认是
abstract
和public
的 - 接口属性默认是
public
、static
和final
的 - 接口不能包含构造函数(因为它不能用于创建对象)
为何以及何时使用接口?
1) 实现安全性——隐藏某些细节,只显示对象(接口)的重要细节。
2) Java 不支持“多重继承”(一个类只能继承自一个超类)。然而,可以通过接口实现多重继承,因为一个类可以实现多个接口。注意:要实现多个接口,请用逗号将它们分隔开(请参阅下面的示例)。
多个接口
要实现多个接口,请用逗号将它们分开
示例
interface FirstInterface {
public void myMethod(); // interface method
}
interface SecondInterface {
public void myOtherMethod(); // interface method
}
class DemoClass implements FirstInterface, SecondInterface {
public void myMethod() {
System.out.println("Some text..");
}
public void myOtherMethod() {
System.out.println("Some other text...");
}
}
class Main {
public static void main(String[] args) {
DemoClass myObj = new DemoClass();
myObj.myMethod();
myObj.myOtherMethod();
}
}