previous | start | next

Implementing MouseListener: 4

If only one instance of a class is to be created and that instance is just passed as a parameter to another method, it seems extravagant to create a named class.

Java allows creating anonymous classes (unnamed classes) from interfaces or from parent classes.

Here is how we could create an object that implements the MouseListener interface without creating a named class:

    MouseListener listener = 
      new MouseListener()
      {
         public void mousePressed(MouseEvent event)
         {  
            int x = event.getX();
            int y = event.getY();
            component.moveTo(x, y);
         }
         // Do-nothing methods
         public void mouseReleased(MouseEvent event) {}
         public void mouseClicked(MouseEvent event) {}
         public void mouseEntered(MouseEvent event) {}
         public void mouseExited(MouseEvent event) {}
    
      });
    component.addMouseListener(listener);

Alternatively, we could replace the interface name MouseListener above by the class name MouseAdapter and omit the Do-nothing methods.



previous | start | next