Objects, Classes, and Interfaces |
To create an interface, you must write both the interface declaration and the interface body.The interfaceDeclaration declares various attributes about the interface such as its name and whether it extends another interface. The interfaceBody contains the constant and method declarations within the interface.interfaceDeclaration { interfaceBody }The Interface Declaration
At minimum, the interface declaration contains the Java keywordinterface
and the name of the interface that you are creating:Note: By convention, interface names begin with capital letters just like class names do. Often, interface names end with "able" or "ible".interface Countable { . . . }An interface declaration can have two other components: the
public
access specifier and a list of "superinterfaces". (An interface can extend other interfaces just as a class can extend or subclass another class.) Thus, the full interface declaration can look like this:The[public] interface InterfaceName [extends listOfSuperInterfaces] { . . . }public
access specifier indicates that the interface can be used by any class. If you do not specify that your interface is public, then your interface will only be accessible to classes that are defined in the same package as the interface.The
extends
clause is similar to theextends
clause in a class declaration, however, an interface can extend multiple interfaces (while a class can only extend one), and an interface cannot extend classes. The list of superinterfaces is a comma-delimited list of all of the interfaces extended by the new interface.The Interface Body
The interface body contains the method signatures for all of the methods within the interface. In addition, an interface can contain constant declarations.Each method signature is followed by a semicolon (;) because an interface does not provide implementations for the methods declared within it. All of the methods declared within the interface body are implicitly abstract.interface Countable { final int MAXIMUM = 500; void incrementCount(); void decrementCount(); int currentCount(); int setCount(int newCount); }
Objects, Classes, and Interfaces |