ADAPTER CLASSES




Adapter classes

Many listener interfaces have more than one callback method. An example is java.awt.FocusListener that has two methods; focusGained(java.awt.FocusEvent event) and focusLost(java.awt.FocusEvent event). When creating a listener class that implements the interface the Java compiler insists that all the interface methods are implemented, which often results in many empty methods being created to satisfy its requirements when only one or some of its methods actually contain code. The following statement shows a FocusListener being used to perform some logic when a Java bean gains focus. However, an empty focusLost method must be provided.
Java bean.addFocusListener(new java.awt.event.FocusListener() {      
    public void focusGained(java.awt.event.FocusEvent e) {          
        doFocusGainedCode();      
     }          
        public void focusLost(java.awt.event.FocusEvent e) {      
     }  
});
To avoid having many empty listener methods for many listeners, Adapter classes are provided. These implement the listener interface, and provide empty (no operation) implementation of its methods. The advantage is that the listener can extend these, and only specialize methods of choice without having to provide default implementations for the rest (these are inherited from the Adapter).
Java bean.addFocusListener(new java.awt.event.FocusAdapter() {     
     public void focusGained(java.awt.event.FocusEvent e) {          
         doFocusGainedCode();      
         }  
   });

Image result for adapter class

Adapter class : 

use only which you need.
Listener Interface : 
use all you can leave blank if you do not need.



No comments:

Post a Comment