Programs

What is Adapter Class in Java? Advantages of Adapter Class and its Types

What Is An Adapter-Class?

In JAVA, an adapter class allows the default implementation of listener interfaces. The notion of listener interfaces stems from the Delegation Event Model. It is one of the many techniques used to handle events in Graphical User Interface (GUI) programming languages, such as JAVA.

GUI programming is predominantly event-driven, with the user interacting with the system through associated visuals and graphics. This means that every activity initiated by the user, such as a mouse’s movement that changes the mouse pointer’s coordinates on the screen, clicks a button or scrolling a page, is considered an independent event. 

Each of these independent event activities is intrinsically linked to a code segment that iterates what response the application should provide to the user. The pathway is simple. The user (source) generates an event and sends it to one or more listener interfaces. Once an event potential is received, the listener interface processes the event and returns the suitable response.

This pathway substantiates the process of event handling. An adapter class in JAVA is therefore used to implement an interface having a set of dummy methods. If a programmer chooses to inherit an adapter class, they will not be forced to implement all the methods listed under a particular listener interface. The adapter class can further be subclassed so that the programmer can override only required methods. In other words, by using an adapter class, the programmer can rapidly construct their own listener interface to field events. This helps save code. 

What Is The Relationship Between An Adapter Class and a Listener Interface?

Listeners are used when the programmer intends to utilize most of the methods listed under the interface. If a listener interface is implemented directly by a class, all the methods within that interface need to be implemented, making the code unreasonably large. This complexity can be resolved by calling upon an adapter class. An adapter class proves essential in instances where an event calls for only specific methods.

The programmer has only to create a subclass of it and override the interest methods to use an adapter class. Adapter classes are, therefore, beneficial for listener interfaces in JAVA having more than one method. To better understand this, let us consider the example of the MouseListener interface. This interface is notified whenever there is a change in the state of the mouse. It has five methods, mouse clicked, mouseExited, mouseEntered, mousePressed, and mouseReleased.

When notified against an event, even if only of these methods is necessary, all of them need to be implemented. The methods that are not needed are kept empty. An adapter class is used to avoid this unnecessary implementation of an empty method body. 

Understanding The Adapter Design Pattern

In non-technical parlance, an adapter, by definition, is structurally designed to allow two incompatible interfaces to work together. An adapter pattern is therefore capable of making two incompatible interfaces compatible without changing their existing code. The corresponding interfaces may be inconsistent, but their inner functionalities should match the requirement being sought. To better clarify this, let us consider a relevant example. 

We are aware that different countries have different electric sockets, voltages, and frequency measurements. If we have to make use of an appliance designed per one country’s specification in another, we need to make sure the appliance is compatible.

For instance, in the UK, type G sockets are commonly used, in the US and Japan, type A and type B sockets, and in India, type C, type D, and type M. A laptop or mobile device carried from India will therefore be incompatible with the electric specifications of say, US and Japan. This is where an adapter’s purpose becomes essential for converting an incompatible code into a compatible code. 

Types of Adapter Classes

Adapter classes can be found in java. awt.the event, java.awt.dnd and java.swing.event packages. The standard adapter classes with their corresponding listener interfaces in JAVA are mentioned below for each of these packages. 

 1. java. awt. eve

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

 2. java.awt.dnd

Adapter Class Listener Interface
DragSourceAdapter DragSourceListener
DragTargetAdapter DragTargetListener

3. javax.swing.event

Adapter Class Listener Interface
MouseInputAdapter MouseInputListener
InternalFrameAdapter InternalFrameListener

These are present in the Abstract Window Toolkit of their respective Java packages. To understand the nature of methods contained within listener interfaces, let us consider a few examples:

  1. The WindowListener interface defines methods related to window events, including opening and closing of a window, activation and deactivation of a window, and the iconification and detoxification of a window.
  2. The KeyListener interface defines methods that handle key events that are fired by the user interacting with keyboard components. 
  3. The MouseListener interface is notified when a mouse is stable and receives event potential related to exiting, entering, clicking, pressing, or releasing component on the user’s visual frame. 
  4. The Component Listener interface receives component event potentials. Here, a component refers to any graphical object designed to interact with the user, such as buttons, checkboxes, and scroll bars. 

Difference Between Class Adapter and Object Adapter

To guarantee functionality and flexibility, object-oriented programming such as JAVA offers programmers features such as inheritance and composition. If you try to reuse a particular code by inheriting its features from another class, the subclass you create will remain dependent on the parent class throughout the entire program’s length.

This makes the system, in many cases, increasingly complex and less testable and makes the exchange of functionality at run-time painstakingly hard. In composition, one class only uses another. Decoupling between the two is further promoted by clearly defining the interfaces.

The debate between class adapter versus object adapter can therefore be resolved as follows. Class Adapter uses inheritance and is therefore capable of only wrapping a class. It cannot wrap an interface because, by definition, it must derive from some base class. An object adapter uses composition and is therefore capable of wrapping both classes and interfaces. This is primarily achieved because, in composition, each class or interface is a private, encapsulated member. 

Advantages of an Adapter Class

  1. An adapter class assists unrelated classes in working together.
  2. With the use of an adapter class, the same class can be used in multiple ways. 
  3. Users are provided with the option of a pluggable kit for developing applications. Class usage, therefore, becomes highly reusable. 
  4. It enhances the transparency of classes. 
  5. It provides a way to include related patterns in a class. 

Learn Software Engineering Courses online from the World’s top Universities. Earn Executive PG Programs, Advanced Certificate Programs, or Masters Programs to fast-track your career.

Conclusion

With this article, we have understood the mechanics of an adapter class in JAVA, the three main packages that contain adapter classes, and the benefits of adapter classes to programmers. Adapter classes are abstract classes for receiving various events and exist as a convenience for creating listener objects. With their different functionalities, adapter classes offer programmers the platform to be innovative via Swing methodology.

If you wish to improve your Java skills, you need to get your hands on these java projects. If you’re interested to learn more about Java, full-stack development, check out upGrad & IIIT-B’s Executive PG Program in Full-stack Software Development, which is designed for working professionals and offers 500+ hours of rigorous training, 9+ projects, and assignments, IIIT-B Alumni status, practical hands-on capstone projects & job assistance with top firms.

What is adapter class in Java?

Adapter class is a class that is defined using the adapter pattern. An adapter can be used to add new capabilities to an existing class without modifying the original class. For example, the java.util.Scanner class is from java.util package. The Scanner class cannot read from a file as a file is not an InputStream. To read from a file we create an adapter class that accepts an InputStream as an argument and returns the processed data as an object. Adapter pattern is used to extend the functionality of an existing class without modifying its code in any way.

What are design patterns in Java?

A design pattern is a general reusable solution to a commonly occurring problem within a given context in software design. It is not a finished design that can be transformed directly into code. It is a description or template for how to solve a problem that can be used in many different situations. In object-oriented programming, design patterns are established conventions that ease the design and implementation of software systems. There are several design patterns in Java. It is not necessary that a design pattern has to be taken from another language. Design patterns can be written in a very simple and short form.

Which is the most used design pattern in Java?

You will find many design patterns in java. The single most used design pattern is Factory Pattern. It has many applications in enterprise development. It helps in removing dependency on concrete classes in the application. Let us give you a real-life example. In an e-commerce application, you might have a requirement to create an object of a user in both test and production environment. The user class may have many subclasses like Admin, Shopkeeper, Seller, User etc. The common main method in factory pattern looks like: public class UserFactory { public static Object create () { User user = createAdmin (); // see if admin is allowed return user ; // return current user } }. See here how the user class is not dependent on concrete class. Although it's not a complete example, it shows you how the Factory pattern works.

Want to share this article?

Land on Your Dream Job

Leave a comment

Your email address will not be published. Required fields are marked *

Leave a comment

Your email address will not be published. Required fields are marked *

×
Get Free career counselling from upGrad experts!
Book a session with an industry professional today!
No Thanks
Let's do it
Get Free career counselling from upGrad experts!
Book a Session with an industry professional today!
Let's do it
No Thanks