John Quach wrote:Or how does implementing Runnable gives you methods for Threads?
Let's deal with that one, because it's easier. Listener is part of a
pattern that involves callbacks, so it takes a bit more thought.
Q: How do you start a Runnable?
A: You start it by creating a
Thread that takes
your Runnable as a parameter.
Thread is
not an interface, it's a fully-functioning class; so it's quite reasonable that it might "understand" how to start a Runnable, since a Runnable class
must implement a
run() method (because it's declared in the interface).
So essentially what you're saying to the new Thread is: "here's a Runnable object; run its
run() method for me".
The polymorphic part is that the Thread doesn't need to know
what type of object it's running; all it needs to know is that it has a
run() method. I can have 563 different types of Runnable, and the way I run them will be identical.
And furthermore, the
mechanism is identical to that with the Shape example: In that case, I (you) created the interface; in this case the
Java designers have provided it for you; and what they both are is
abstractions that allow a client (in the case of the Shape, a
for loop; in the case of Runnable, a Thread class) to know only what it needs to fulfill a task (in the case of Shape: how to
draw() it; in the case of Runnable: how to
run() it).
If you follow that, then we can go on to Listeners.
Winston