Java Reference
In-Depth Information
accounts can be instantiated. The following statement created the Vector object
accountsList and the element type is BankAccount :
Vector <BankAccount> accountsList = new Vector <BankAccount>();
We leave it as an exercise for you to write the definitions of the classes described in this
example as well as a program to test these classes. (See Programming Exercise 14 at the
end of this chapter.)
Interfaces
In Chapter 6, you learned that the class ActionListener is a special type of class
called an interface . Several other classes in Java are similar to the interface
ActionListener . For example, window events are handled by the interface
WindowListener , and mouse events are handled by the interface MouseListener .
Theobviousquestionis:WhydoesJavahavethese interfaces? After all, they are similar
to classes. The answer is that Java does not support multiple inheritance; a class can extend
the definition of only one class. In other words, a class can be derived from only one
existing class. However, a Java program might contain a variety of GUI components and
thus generate a variety of events, such as window events, mouse events, and action
events. These events are handled by separate interfaces. Therefore, a program might
need to use more than one such interface.
Until now, we have handled events by using the mechanism of the inner class. For example,
action events were processed by using inner classes. There are two more ways, discussed in
Chapter 11, to process events in a Java program—by using anonymous classes and by making
the class containing the application program implement the appropriate interface.
When we created an inner class to process an action event, the inner class was built on
top of the interface ActionListener by using the mechanism of implements .
Rather than use the inner class mechanism, the class containing the Java program can
itself be created on top of (''by implementing'') an interface, just as we created the GUI
program by extending the class JFrame . For example, for the RectangleProgram in
Chapter 6, we could have defined the class RectangleProgram as follows:
1
0
public class RectangleProgram extends JFrame implements
ActionListener
{
//...
}
Of course, doing so would also require us to register the listener using the reference
this , which was explained in Chapter 8.
To be able to handle a variety of events, Java allows a class to implement more than one
interface. This is, in fact, how Java implements a form of multiple inheritance, which is not true
multiple inheritance. In the remainder of this section, we provide a few facts about interfaces.
 
 
Search WWH ::




Custom Search