What is Java Adapter Class?


Java Adapter Class is a class that provides an empty implementation of an interface. It is used as a placeholder for implementing only the required methods of an interface. Adapter classes are useful when you want to create a listener for an event, but you don't want to implement all the methods of the listener interface.

For example, let's say we have a MouseListener interface that has five methods: mouseClicked(), mouseEntered(), mouseExited(), mousePressed(), and mouseReleased(). If we want to create a listener for only the mouseClicked() method, we can use an adapter class to provide empty implementations for the other four methods.

Here's an example of how to use an adapter class for a MouseListener:

import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

public class MyMouseListener extends MouseAdapter {
    public void mouseClicked(MouseEvent e) {
        System.out.println("Mouse clicked");
    }
}

In this example, we create a class called MyMouseListener that extends the MouseAdapter class. We override the mouseClicked() method to print out a message when the mouse is clicked. Since we're only interested in the mouseClicked() method, we don't need to implement the other four methods of the MouseListener interface.

Another example of using an adapter class is with the WindowListener interface. This interface has seven methods, but we may only be interested in the windowClosing() method. Here's an example of how to use an adapter class for a WindowListener:

import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

public class MyWindowListener extends WindowAdapter {
    public void windowClosing(WindowEvent e) {
        System.out.println("Window is closing");
    }
}

In this example, we create a class called MyWindowListener that extends the WindowAdapter class. We override the windowClosing() method to print out a message when the window is closing. Since we're only interested in the windowClosing() method, we don't need to implement the other six methods of the WindowListener interface.



About the author

William Pham is the Admin and primary author of Howto-Code.com. With over 10 years of experience in programming. William Pham is fluent in several programming languages, including Python, PHP, JavaScript, Java, C++.