Table of contents
1.
Introduction
2.
Java Adapter class 
3.
Relationship Between Java Adapter Class and Listener Interface
4.
Types of Java Adapter Classes
4.1.
java.awt.event Adapter classes
4.2.
java.awt.dnd Adapter classes
4.3.
javax.swing.event Adapter classes
5.
Example of Java Adapter Classes
5.1.
Java WindowAdapter 
5.2.
Java MouseMotionAdapter 
6.
Advantages of Java Adapter Class 
7.
Frequently Asked Questions
7.1.
Why do we need Java adapter classes?
7.2.
What is the adapter class in Java?
7.3.
Differentiate between the Java Adapter class and Java Listener Interface. 
7.4.
What is an adapter and types?
8.
Conclusion
Last Updated: Aug 29, 2024
Medium

Java Adapter class

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Java is a well-known general-purpose, object-oriented programming language based on classes with minimal implementation requirements. It is a computer platform for application development. As a result, Java is a fast, secure, and dependable programming language. It is commonly used to build Java applications in laptops, data centers, game consoles, scientific supercomputers, cell phones, and other locations.

The Java adapter class is the default implementation of listener interfaces in Java offered via adapter classes. We do not have to implement all listener interface functions if we inherit the Java adapter class. As a result, much code is saved. 

Java Adapter class

The following article will look into Java adapter classes in detail.

Also Read About, Multithreading in java and Hashcode Method in Java

Java Adapter class 

A Java adapter class allows listener interfaces to be implemented by default. The Delegation Event Model gave rise to the concept of listener interfaces. It is one of the various strategies used to handle events in Graphical User Interface (GUI) programming languages like Java.

In most event-driven GUI development, the user interacts with the system through related images and graphics. This means any action done by the user is regarded as a separate event, such as moving the mouse pointer on the screen to change its coordinates, clicking a button, or scrolling a page.

These different event activities are inextricably linked to a code segment that iterates the application's response to the user. The path is pretty straightforward. The user generates an event that is sent to one or more listener interfaces. When an event potential is received, the Listener Interface analyses it and responds appropriately.

This path validates the event handling process. A Java adapter class implements an interface with a set of dummy methods. When programmers inherit a Java adapter class, they are not obligated to implement all of the methods mentioned under each listener interface. The adapter class can also be subclassed, allowing the programmer to override only the required methods. In other words, a programmer can quickly create their listener interface to field events by utilizing a Java adapter class—this aids in the reduction of code.

Read More About, Basics of Java

Relationship Between Java Adapter Class and Listener Interface

Listeners are used when a programmer intends to use the majority of the methods given in the interface. If a class implements a listener interface directly, it must implement all of the interface's functions, resulting in overly long code. The use of a Java adapter class can aid in the resolution of this issue. A Java adapter class comes in helpful when an event requires a few specialized methods.

To use a Java adapter class, the programmer only needs to create a subclass of it and override the interest methods. Java Adapter classes are advantageous for Java listener interfaces with several methods.

Types of Java Adapter Classes

Java adapter classes can be found in java.awt.event, java.awt.dnd, and javax.swing.event packages. The adapter classes are listed below, along with their listener interfaces.

java.awt.event Adapter classes

Java adapter class

Java Listener interface

WindowAdapter WindowListener
KeyAdapter KeyListener
MouseAdapter MouseListener
MouseMotionAdapter MouseMotionListener
FocusAdapter FocusListener
ComponentAdapter ComponentListener
ContainerAdapter ContainerListener
HierarchyBoundsAdapter HierarchyBoundsListener

java.awt.dnd Adapter classes

Java adapter class

Java Listener interface

DragSourceAdapter DragSourceListener
DragTargetAdapter DragTargetListener

javax.swing.event Adapter classes

Java Adapter class

Java Listener interface

MouseInputAdapter MouseInputListener
InternalFrameAdapter InternalFrameListener

Example of Java Adapter Classes

Java WindowAdapter 

The WindowAdapter class of AWT is implemented in the following example, and one of its methods, windowClosing() is used to close the frame window.

// importing the necessary libraries  
import java.awt.*;    
import java.awt.event.*;    
  
public class AdapterExample {  
// object of Frame    
    Frame f;    
    
// class constructor  
    AdapterExample() {    
// creating a frame with the title  
        f = new Frame ("Window Adapter");    
// adding the WindowListener to the frame  
// overriding the windowClosing() method   
        f.addWindowListener (new WindowAdapter() {    
            public void windowClosing (WindowEvent e) {    
                f.dispose();    
            }    
        });    
         // setting the size, layout and   
        f.setSize (400, 400);    
        f.setLayout (null);    
        f.setVisible (true);    
    }    
  
// main method  
public static void main(String[] args) {    
    new AdapterExample();    
}    
}    
You can also try this code with Online Java Compiler
Run Code

Java MouseMotionAdapter 

The MouseMotionAdapter class and its various methods are implemented in the following example to listen to mouse motion events in the Frame window.

// importing the necessary libraries  
import java.awt.*;    
import java.awt.event.*;   
 
// class which inherits the MouseMotionAdapter class  
public class MouseMotionAdapterExample extends MouseMotionAdapter {     

// object of Frame class  
    Frame f;    

// class constructor  
    MouseMotionAdapterExample() {    
// creating the frame with the title  
        f = new Frame ("Mouse Motion Adapter");    
// adding MouseMotionListener to the Frame  
        f.addMouseMotionListener (this);    
 // setting the size, layout and visibility of the frame  
        f.setSize (300, 300);    
        f.setLayout (null);    
        f.setVisible (true);    
    }    

// overriding the mouseDragged() method   
public void mouseDragged (MouseEvent e) {    
// creating the Graphics object and fetching them from the Frame object using getGraphics() method  
    Graphics g = f.getGraphics();    
// setting the color of graphics object  
    g.setColor (Color.ORANGE);    
// setting the shape of graphics object  
    g.fillOval (e.getX(), e.getY(), 20, 20);    
}    

public static void main(String[] args) {    
    new MouseMotionAdapterExample();    
}    
}    
You can also try this code with Online Java Compiler
Run Code

Output:

Output of Java MouseMotionAdapter

 

You can practice by yourself with the help of online java compiler.

Check out this article - Upcasting and Downcasting in Java

Advantages of Java Adapter Class 

The advantages of Java adapter class area as follows:-

  • With the help of the Java adapter class, unrelated classes can work together.
  • With the help of a Java adapter class, the same class can be used in multiple ways.
  • Users can construct apps with the help of a pluggable kit. As a result, class is reused a lot.
  • Java adapter class helps to make classes more visible.
  • Java adapter classes allow us to put patterns in a class together.
  • Java adapter classes allow courses that are not connected to collaborate more easily.
  • Java adapter classes give us the flexibility to use classes in a variety of ways.
  • Java adapter classes help to make classes more visible.
  • Java adapter classes permit similar patterns to be included in the class.
  • Java adapter class comes with a pluggable app development kit.
  • Java adapter class increases the reusability of the class.

    You can also read about the Multiple Inheritance in Java and, Has-A Relationship in Java.

Frequently Asked Questions

Why do we need Java adapter classes?

Java adapter classes are used by default to implement listener interfaces. We will not have to implement all listener interface functions if we inherit the adapter class. As a result, the code is saved.

What is the adapter class in Java?

An adapter class in Java provides default implementations for methods in listener interfaces, simplifying the creation of event handlers.

Differentiate between the Java Adapter class and Java Listener Interface. 

An adapter class does not need to implement all of the methods in an interface. When only a handful of the interface's methods need to be modified, this method is utilized. A listener's interface must have all of the methods defined in it implemented.

What is an adapter and types?

An adapter is a design pattern that allows interfaces of incompatible objects to work together. Types include class, object, and interface adapters.

Conclusion

In this article, we have extensively discussed the Java adapter classes. We began with a brief introduction to Java adapter classes, followed by a detailed explanation and key examples.

After reading about the Java adapter classes, are you not feeling excited to read/explore more articles on Java? Don't worry; Coding Ninjas has you covered. To learn, see  Basics of Java with Data Structures and AlgorithmsJava foundation for free, Java AWT Tutorial, and Difference between AWT and Swing, And Fibonacci Series in Java

Refer to our Guided Path on Coding Ninjas Studio to upskill yourself in Data Structures and Algorithms, Competitive Programming, JavaScript, System Design, and many more! If you want to test your competency in coding, you may check out the mock test series and participate in the contests hosted on Coding Ninjas Studio! But if you have just started your learning process and are looking for questions asked by tech giants like Amazon, Microsoft, Uber, etc; you must look at the problems, interview experiences, and interview bundle for placement preparations.

Nevertheless, you may consider our paid courses to give your career an edge over others!

Do upvote our blogs if you find them helpful and engaging!

Live masterclass