What is the function of adapter in java model?

Java

1 answer

Answer

1255061

2026-09-06 16:45

+ Follow

An Adapter is simply a concrete class which implements all the methods of a Listener interface as empty functions. They are convenience classes made because of the tendency to implement Listeners as anonymous classes.

For example, let's say we want to add a Listener to a JFrame to detect a mouse click:

// implementing a Listener

JFrame frame = new JFrame();

frame.addMouseListener(new MouseListener() {

void mouseClicked(MouseEvent e) {

// do something here

}

void mouseEntered(MouseEvent e) {

}

void mouseExited(MouseEvent e) {

}

void mousePressed(MouseEvent e) {

}

void mouseReleased(MouseEvent e) {

}

});

Note how this has a lot of extra code that does nothing.

// implementing an Adapter

JFrame frame = new JFrame();

frame.addMouseListener(new MouseAdapter() {

void mouseClicked(MouseEvent e) {

// do something here

}

});

Note now how we only need to implement one method. This is much cleaner and easier to read.

ReportLike(0ShareFavorite

Copyright © 2026 eLLeNow.com All Rights Reserved.