Class 1, Part 2 |
Intro to Java 30-IT-396 |
|
Adapter Classes
-
There are a number of interfaces used for event handing. The ActionListener,
FocusListener, ItemListener, MouseListener, MouseMotionListener, and many
more.
-
Many of these listeners have multiple methods. Since it is an interface,
you theoretically have to write an implementation for each method, even
if it is empty! This is a lot of work.
-
So, Java provides you with Adapters. Adapters are classes
that implement an interface and all of its methods, but leave them all
blank.
-
Then, you can extend the adapter, and only implement the method you
want. All of the others simply use the empty method from the
adapter itself.
-
For example, say you want to listen for a window closing event. The
WindowListener
interface has methods to handle
when the window is activated, closed, iconified, deiconified, and more.
-
Since it is an interface, you have to implement every single method.
-
But you don't care about all of those, you just want to know when the window
closes!
-
That's where the WindowAdapter comes in. The WindowAdapter class
implements each method, but leaves the definition blank. Then, when
you extend WindowAdapter, you only need to implement the method you want.
-
Remember, with dynamic binding, if you implement a method in a subclass,
Java is smart enough to find that in the subclass. If you don't implement
it, Java will just go to the parent class.
-
Note to self: Draw some UML in Poseidon or on the
board to represent this.
Created by: Brandan
Jones January 4, 2002