Java Reference
In-Depth Information
If the methods have different argument lists, it is a simple case of method over-
loading; you implement both method signatures, and each definition satisfies its
respective interface definition.
n
If the methods have the same argument lists but differ in return type, you cannot
create a method that satisfies both. (Remember that method overloading is trig-
gered by parameter lists, not by return type.) In this case, trying to compile a class
that implements both interfaces produces a compiler error message. Running across
this problem suggests that your interfaces have some design flaws that you might
need to reexamine.
n
Other Uses of Interfaces
Remember that almost everywhere that you can use a class, you can use an interface
instead. For example, you can declare a variable to be of an interface type:
Iterator loop = new Iterator()
When a variable is declared to be of an interface type, it simply means that the object is
expected to have implemented that interface. In this case, because Iterator contains an
object of the type Iterator , the assumption is that you can call all three of the inter-
face's methods on that object: hasNext() , next() , and remove() .
The important point to realize here is that although Iterator is expected to have the
three methods, you could write this code long before any classes that qualify are actu-
ally implemented.
You also can cast objects to an interface, just as you can cast objects to other classes.
Creating and Extending Interfaces
After you use interfaces for a while, the next step is to define your own interfaces.
Interfaces look a lot like classes; they are declared in much the same way and can be
arranged into a hierarchy. However, you must follow certain rules for declaring inter-
faces.
New Interfaces
To create a new interface, you declare it like this:
interface Expandable {
// ...
}
 
Search WWH ::




Custom Search