Documentation

The Java™ Tutorials
Hide TOC
Defining an Interface定义接口
Trail: Learning the Java Language
Lesson: Interfaces and Inheritance
Section: Interfaces

Defining an Interface定义接口

An interface declaration consists of modifiers, the keyword interface, the interface name, a comma-separated list of parent interfaces (if any), and the interface body. 接口声明由修饰符、关键字interface、接口名称、以逗号分隔的父接口列表(如果有)和接口体组成。For example:例如:

public interface GroupedInterface extends Interface1, Interface2, Interface3 {

    // constant declarations
    
    // base of natural logarithms
    double E = 2.718282;
 
    // method signatures
    void doSomething (int i, double x);
    int doSomethingElse(String s);
}

The public access specifier indicates that the interface can be used by any class in any package. public访问说明符表示接口可由任何包中的任何类使用。If you do not specify that the interface is public, then your interface is accessible only to classes defined in the same package as the interface.如果未指定接口为公共接口,则只有在与接口相同的包中定义的类才能访问接口。

An interface can extend other interfaces, just as a class subclass or extend another class. 一个接口可以扩展其他接口,就像一个类的子类或扩展另一个类一样。However, whereas a class can extend only one other class, an interface can extend any number of interfaces. 然而,一个类只能扩展另一个类,而一个接口可以扩展任意数量的接口。The interface declaration includes a comma-separated list of all the interfaces that it extends.接口声明包括一个逗号分隔的列表,其中列出了它扩展的所有接口。

The Interface Body接口主体

The interface body can contain abstract methods, default methods, and static methods. 接口主体可以包含抽象方法默认方法静态方法An abstract method within an interface is followed by a semicolon, but no braces (an abstract method does not contain an implementation). 接口中的抽象方法后跟分号,但不带大括号(抽象方法不包含实现)。Default methods are defined with the default modifier, and static methods with the static keyword. 默认方法使用default修饰符定义,静态方法使用static关键字定义。All abstract, default, and static methods in an interface are implicitly public, so you can omit the public modifier.接口中的所有抽象、默认和静态方法都是隐式公开的,因此可以省略public修饰符。

In addition, an interface can contain constant declarations. 此外,接口可以包含常量声明。All constant values defined in an interface are implicitly public, static, and final. 接口中定义的所有常量值都是隐式publicstaticfinalOnce again, you can omit these modifiers.同样,可以忽略这些修饰符。


Previous page: Interfaces
Next page: Implementing an Interface