Registered User
Registered User

Reputation: 2299

How do the predefined interfaces in java work?

This question is not about how to use interfaces, it is about how some of the predefined interfaces in java work.

For example consider the ActionListener interface from java.awt.event package. When we implement the interface, then we must define the actionPerformed() method which will be called when an action occurs.

What I want to know is how does this work. we aren't writing any code that checks for action occuring and which then calls actionPerformed. Neither is the code in the interface. It happens automatically.

Who is actually doing this work?

Upvotes: 0

Views: 356

Answers (2)

OneCricketeer
OneCricketeer

Reputation: 191728

Not sure what you mean by "predefined" because there is no difference in the ones Java provides or ones that you write.

For example, let's say you are using a MouseListener, and added it to some Component, then that interface gets assigned to a MouseListener field of the component.

Whenever an event from a Mouse is triggered, then this method is called (OpenJDK source). Notice that the interfaces methods are called here. (Note: there's additional work before this to detect that the event was actually caused by a Mouse).

You can imagine, though, that for a Button, the actionPerformed method goes through the same set of logic as a mouse click event.

protected void processMouseEvent(MouseEvent e) {
    MouseListener listener = mouseListener;
    if (listener != null) {
         int id = e.getID();
         switch(id) {
           case MouseEvent.MOUSE_PRESSED:
               listener.mousePressed(e);
               break;
           case MouseEvent.MOUSE_RELEASED:
               listener.mouseReleased(e);
               break;
           case MouseEvent.MOUSE_CLICKED:
               listener.mouseClicked(e);
               break;
           case MouseEvent.MOUSE_EXITED:
               listener.mouseExited(e);
               break;
           case MouseEvent.MOUSE_ENTERED:
               listener.mouseEntered(e);
               break;
         }
     }
 }

Upvotes: 0

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726579

Interfaces such as ActionListener are an implementation of a callback. This means that there are other classes, such as JButton, which check for user action occurring, and know when it happens. Their task is to let your code know when it happens.

They do it by means of calling back actionPerformed method of an ActionListener interface that you pass to them. This approach provides a very clean separation between the UI code, which knows when an action occurs, but does not know what exactly you want to do, and your code, which knows exactly what to do, but does not know when the action occurs.

Upvotes: 3

Related Questions