J2EEOnline J2EEOnline

Classes/Objects  «Prev  Next»
Lesson 7Interface declarations
Objective Describe the declaration and use of interfaces.


Properties of members of an interface

As of Java SE7, the only primitive type an interface can define is a constant. Once the constant is assigned, you cannot change the value of a constant. The variables of an interface are implicitly public, final, and static. For example, the following definition of the interface TestInterface,

interface TestInterface {
 int age = 11;

is equivalent to the following definition:
interface TestInterface {
 public static final int AGE = 11;
Interfaces are used to define one or more methods along with constants (see above) that are implemented by classes. However, they may also define
  1. inner classes, and
  2. inner interfaces.

See the following link for a detailed description of static nested classes and interfaces.
The following example ExecutorService is from the Oracle documentation.
public interface ExecutorService extends Executor {
 // Interface body

Valid modifiers for interfaces are public and abstract, that is the following interface declarations are equivalent.
interface A{}
public interface A{}
public abstract interface A{}

A public interface may be accessed outside of its package. All interfaces are implicitly abstract. The extends clause consists of extends followed by a comma-separated list of interfaces.
An interface can only extend another interface.
For example, if an interface X extends interfaces Y and Z, then X inherits all of the constants and methods of the interfaces Y and Z.

interface Y{
 void draw();
interface Z{
 void move();
public interface X extends Y,Z{

The interface body consists of constant declarations, abstract method declarations, inner classes, and inner interfaces. Inner classes and interfaces are covered later in this module. A constant definition is the declaration and initialization of a variable that is public, static, and final. The variables modifiers are optional.
An abstract method declaration is specified as follows:
modifiers returnType methodName(arguments) throwsClause;

Note the semicolon replaces the method body. Methods are implicitly abstract and public. They may not be declared static, native, final, or synchronized.