Download the JDK
Search the Tutorials
Hide the TOC
Trail: Learning the Java Language
Lesson: Interfaces and Inheritance
Section: Interfaces
Interfaces and Inheritance
Interfaces
Defining an Interface
Implementing an Interface
Using an Interface as a Type
Rewriting Interfaces
Summary of Interfaces
Questions and Exercises
Inheritance
Overriding and Hiding Methods
Hiding Fields
Using the Keyword super
Object as a Superclass
Writing Final Classes and Methods
Abstract Methods and Classes
Summary of Inheritance
Questions and Exercises
Home Page > Learning the Java Language > Interfaces and Inheritance
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. For example:

> >     public interface GroupedInterface extends Interface1,
> >                                             Interface2, Interface3 {

> >        // constant declarations
> >        double E = 2.718282;  // base of natural logarithms

> >        // 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. If you do not specify that the interface is public, your interface will be accessible only to classes defined in the same package as the interface.

> An interface can extend other interfaces, just as a class can extend or subclass 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 contains method declarations for all the methods included in the interface. A method declaration within an interface is followed by a semicolon, but no braces, because an interface does not provide implementations for the methods declared within it. All methods declared in an interface are implicitly `public`, so the public modifier can be omitted.

> An interface can contain constant declarations in addition to method declarations. All constant values defined in an interface are implicitly `public`, `static`, and `final`. Once again, these modifiers can be omitted.

Previous page: Interfaces
Next page: Implementing an Interface