PUB ID

Tuesday, 5 January 2016

What is Adapter class in Java?

  • Adapter class is a simple java class that implements an interface with only EMPTY implementation .
  • Instead of implementing interface if we extends Adapter class ,we provide implementation only for require method 
  • An adapter class provides the default implementation of all methods in an EventListener interface. Adapter classes are very useful when you want to process only few of the events that are handled by a particular event listener interface.
     
    Here's a mouse adapter that beeps when the mouse is clicked


    import java.awt.*;
    import java.awt.event.*;
    
    public class MouseBeeper extends MouseAdapter  {
    
      public void mouseClicked(MouseEvent evt) {
        Toolkit.getDefaultToolkit().beep();
      }
    
    }
    
    Without extending the MouseAdapter class, I would have had to write the same class like this
    import java.awt.*;
    import java.awt.event.*;
    
    
    public class MouseBeeper implements MouseListener  {
    
      public void mouseClicked(MouseEvent evt) {
        Toolkit.getDefaultToolkit().beep();
      }
    
      public void mousePressed(MouseEvent evt) {}
      public void mouseReleased(MouseEvent evt) {}
      public void mouseEntered(MouseEvent evt) {}
      public void mouseExited(MouseEvent evt) {}
    
    }
    
    Adapter classes are a minor convenience. You do not need to use the adapter classes if you don't want to.
     Click here for full tutorial of Adapter Classes
     

No comments:

Post a Comment