Java Reference
In-Depth Information
However, an interface is different from a class in several ways, including:
You cannot instantiate an interface.
■■
An interface does not contain any constructors.
■■
All of the methods in an interface are abstract.
■■
An interface cannot contain instance fields. The only fields that can
appear in an interface must be declared both static and final.
■■
An interface is not extended by a class; it is implemented by a class.
■■
An interface can extend multiple interfaces.
■■
An interface is not a class. Writing an interface is similar to writing a class,
but they are two different concepts. A class describes the attributes and
behaviors of an object. An interface contains behaviors that a class
implements.
Interfaces have many uses and benefits. For example, an interface can be used
to expose certain behaviors of a class, without exposing all of the behaviors of a
class. Interfaces can be used to force behavior on other objects, ensuring that cer-
tain methods are implemented by an object. Interfaces can be used for polymor-
phism reasons, since an object can take on the form of an interface type.
We will discuss all of these uses and benefits of interfaces throughout this
chapter. I want to start by discussing the details of writing interfaces and writ-
ing classes that implement interfaces.
Declaring Interfaces
The interface keyword is used to declare an interface. The source code file for
an interface has the format shown here:
//A package declaration
package package_name;
//Any number of import statements
import java.lang.*;
public interface NameOfInterface
{
//Any number of final, static fields
//Any number of abstract method declarations
}
Interfaces have the following properties:
Search WWH ::




Custom Search