Java Reference
In-Depth Information
It is time to go over details of how to create and use interfaces in a Java program. As I discuss the technical details
of interfaces, I will also go over proper uses and common misuses of interfaces.
Declaring an Interface
An interface can be declared as a top-level interface, a nested interface, or an annotation type. I will discuss nested
interfaces later in this chapter. Annotation type interfaces are discussed in a separate chapter in a different book. I will
use the term
interface
to mean a top-level interface. The general (incomplete) syntax for declaring an interface is
<modifiers> interface <interface-name> {
Constant-Declaration
Method-Declaration
Nested-Type-Declaration
}
An interface declaration starts with list of modifiers, which may be empty. Like a class, an interface can have a public
or package-level scope. The keyword
public
is used to indicate that the interface has a public scope. A public interface
can be referred to from anywhere in the application. Absence of a scope-modifier indicates that the interface has a
package-level scope. An interface with a package-level scope can be referred to only within the members of its package.
The keyword
interface
is used to declare an interface. The keyword is followed by the name of the interface.
The name of an interface is a valid Java identifier. An interface body follows its name, which is placed inside braces.
Members of an interface are declared inside the body. In a special case, the body of an interface can be empty. The
following is the simplest interface declaration:
package com.jdojo.interfaces;
interface Updatable {
// The interface body is empty
}
This code declares an interface named
Updatable
, which has a package-level scope. It can be used only inside the
com.jdojo.interfaces
package because it has a package-level scope. It does not contain any member declarations.
Like a class, an interface has a simple name and a fully qualified name. The identifier that follows the keyword
interface
is its simple name. The fully qualified name of an interface is formed by using its package name and the
simple name separated by a dot. In the above example,
Updatable
is the simple name and
com.jdojo.interfaces.
Updatable
is the fully qualified name. The rules of using simple and fully qualified name of an interface are the same
as that of a class.
The following code declares an interface named
ReadOnly
. It has a
public
scope. That is, the definition of the
ReadOnly
interface is available anywhere in the application, not only inside the
com.jdojo.interfaces
package.
package com.jdojo.interfaces;
public interface ReadOnly {
// The interface body is empty
}
An interface declaration is implicitly
abstract
. You can declare
Updatable
and
ReadOnly
interfaces as follows
without changing their meanings. In other words, an interface declaration is always
abstract
whether you declare it
abstract
explicitly or not.