Calling on an implemented method automatically?

54 views Asked by At

I was curious about how the implements keyword works, and I was hoping someone could explain to me, where does the implemented method get called on?

For example let's say I have a class that implements ActionListener. It now implements the

public void actionPerformed(ActionEvent e) {
}

method. I have a button that is binded to this ActionListener. But how does it call on this method? How does it know my class implements this method.

2

There are 2 answers

0
pkozlov On BEST ANSWER

This is called "dynamic binding" in Java. You can read this on details here, for example http://www.studytonight.com/java/dynamic-method-dispatch.php

0
Hovercraft Full Of Eels On

It knows your class implements the listener because the parameter to the addActionListener(...) method only accepts classes that implement the ActionListener interface. It calls the method because in the internals within AbstractButton, it knows that all the objects within its List that holds these listeners, implements the ActionListener interface and thus has the actionPerformed method. For greater details, consider looking at the source code of AbstractButton, and you'll see exactly where it does this. Google can help you find the source if you don't already have the src.zip file on disk.