Java Reference
In-Depth Information
■
It is a convention to use all uppercase letters in the name of a field in an interface to indicate that they are
constants. however, Java does not impose any restrictions on naming the fields of an interface as long as they follow the
naming rules for identifiers. fields of an interface are always
public
. however, the accessibility of
public
fields from
outside the declaring package depends on the scope of the interface. for example, if an interface is declared to have
a package-level scope, its fields are not accessible outside the package because the interface itself is not accessible
outside the package, even though its fields are always
public
.
Tip
You are advised not to declare an interface to only have constant fields in it. The proper (and most commonly
used) use of an interface is to declare a set of methods to define APIs. If you want to group constants in one construct,
use a class, not an interface. If you are using Java 5 or a higher version, consider using enum to declare your constants.
Using enum provides type safety and compile-time checks for your constants.
Methods Declarations
You can declare three types of methods in an interface:
•
Abstract methods
•
Static methods
•
Prior to Java 8, you could declare only abstract methods in interfaces. The modifiers
static
and
default
are
used to declare static and default methods, respectively. The lack of
static
and
default
modifiers makes a method
abstract. The following is an example of an interface with all three types of methods:
Default methods
interface AnInterface {
// An abstract method
int m1();
// A static method
static int m2() {
// The method implementation goes here
}
// A default method
default int m3() {
// The method implementation goes here
}
}
The following sections discuss each method type declaration in detail.
Abstract Methods Declarations
The main purpose of declaring an interface is to create an abstract specification (or concept) by declaring zero or
more
abstract
methods. All method declarations in an interface are implicitly
abstract
and
public
unless they are
declared
static
or
default
. Like in a class, an abstract method in an interface does not have an implementation.