Java interface 关键字
实例
interface
接口是一个抽象的 "类",用于将相关方法与 "空" 主体分组:
interface Animal {
public void animalSound(); // interface method (does not have a body)
public void sleep(); // interface method (does not have a body)
}
class Pig implements Animal {
public void animalSound() {
System.out.println("The pig says: wee wee");
}
public void sleep() {
System.out.println("Zzz");
}
}
public class Main {
public static void main(String[] args) {
Pig myPig = new Pig();
myPig.animalSound();
myPig.sleep();
}
}
定义与用法
interface
关键字用于声明仅包含抽象方法的特殊类型的类。
要访问接口方法,接口必须由另一个带有 implements
关键字(而不是 extends
)的类 "实现"(有点像继承)。接口方法的主体由 "implement" 类提供:
关于接口的说明:
- 与抽象类一样,接口不能用于创建对象(在上面的实例中,不可能在 MyMain 类中创建 "Animal" 对象)
- 接口方法没有主体——主体由 "implement" 类提供
- 在实现接口时,必须覆盖其所有方法
- 默认情况下,接口方法是
abstract
抽象的和public
公共的 - 接口属性默认为
public
、static
和final
- 接口不能包含构造函数(因为它不能用于创建对象)
为什么以及何时使用接口?
1) 为了实现安全性——隐藏某些细节,只显示对象(接口)的重要细节。
2) Java 不支持 "多继承"(一个类只能从一个超类继承)。但是,它可以通过接口实现,因为该类可以 实现 多个接口。
注意:要实现多个接口,请用逗号分隔它们(参见下面的实例)。
多个接口
要实现多个接口,请用逗号分隔它们:
实例
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...");
}
}
public class Main {
public static void main(String[] args) {
DemoClass myObj = new DemoClass();
myObj.myMethod();
myObj.myOtherMethod();
}
}
关联页面
阅读有关接口的更多知识,可以访问本站的 Java Interface